Skip to content

Instantly share code, notes, and snippets.

@superjojo140
Last active March 5, 2020 16:37
Show Gist options
  • Save superjojo140/ae35d797db2354ce36d3dfea3c915cad to your computer and use it in GitHub Desktop.
Save superjojo140/ae35d797db2354ce36d3dfea3c915cad to your computer and use it in GitHub Desktop.
Content Type in HTTP Requests

The Content-Type header is used to specify how the data in the body of a HTTP request or response is formatted.

Possible Values

There are really a lot of possible values. The most common values for HTTP Requests are listed here. For a more completely list see MDN - MIME types

application/json

A stringified JSON object is transmitted as body of the request

Example Request:

POST /test HTTP/1.1
Host: foo.example
Content-Type: application/json

{"username": "John Doe", "timezone": "US/Pacific", "orders" : [12,34]}

application/x-www-form-urlencoded

The keys and values are encoded in key-value tuples separated by '&', with a '=' between the key and the value.

Example Request:

POST /test HTTP/1.1
Host: foo.example
Content-Type: application/x-www-form-urlencoded

field1=value1&field2=value2

multipart/form-data

The Content-Type header contains a boundary attribute that defines a random string separating the individual values.

Each value is described by content disposition attributes. This is followed by the value in the next line

Example Request:

POST /test HTTP/1.1 
Host: foo.example
Content-Type: multipart/form-data;boundary="randomBoundaryString" 

randomBoundaryString
Content-Disposition: form-data; name="field1" 

value1 
randomBoundaryString
Content-Disposition: form-data; name="field2"; filename="example.txt" 

value2
randomBoundaryString

text/plain

Plain text is transmitted. The receiver must know how to deal with the received information.

Example Request:

POST /test HTTP/1.1
Host: foo.example
Content-Type: text/plain

This is a very informative text. Enjoy it!

text/html

Html Code is transmitted as body of the request. This is a normal used to deliver a website as response to a GET Request.


Example Response:

Status: 200
Content-Type: text/html

<!DOCTYPE html>
<html lang="en" dir="ltr">
  <meta charset="utf-8">
  <title>Awesome Website</title>
  ...
</html>


How to set Content-Type when sending a Request / Response

Javascript fetch API

const response = await fetch(url, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify(data)
  });

JQuery.ajax

$.ajax({
  method: "POST",
  url: "someUrl.php",
  data: { name: "John", location: "Boston" },
  contentType : "'application/json; charset=UTF-8'"
})

axios

axios({
  method: 'post',
  url: '/user/12345',
  data: {
    firstName: 'Fred',
    lastName: 'Flintstone'
  },
  headers: { 'content-type': 'application/json' }
});

Express.js

res.set('Content-Type', 'applictaion/json')

PHP

header('Content-Type: application/json');

Always set headers before sending (or echo) any data



How to read the Content Type and parse data

Javascript fetch API

Use the fitting of the follwing promises on the response object returned by the fetch() promise

$.ajax({
  const responseData = await response.json(); 
  const responseData = await response.arrayBuffer(); 
  const responseData = await response.blob();  
  const responseData = await response.text();  
  const responseData = await response.formData(); 
})

jQuery.ajax

Use dataType option
Options are: xml, json, script, html and more

$.ajax({
  method: "GET",
  url: "someUrl.php",
  dataType: "json",
  success: (responseData) => {
    console.log(responseData.username)
    }
})

axios

responseType option indicates the type of data that the server will respond with
Options are 'arraybuffer', 'blob', 'document', 'json' (default), 'text', 'stream'

const response = await axios({
  method: 'get',
  url: 'someUrl',
  responseType: 'json'
});

console.log(response.data.userName);

Express.js

var bodyParser = require('body-parser')

app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())

app.post('/login', function (req, res) {
  console.log('Welcome: ' + req.body.username)
})

PHP

Read application/json data:

// Takes raw data from the request
$json = file_get_contents('php://input');

// Converts it into a PHP object
$data = json_decode($json);

$val1 = $data["key1"];

Read application/x-www-form-urlencoded or multipart/form-data data:

$val1 = $_POST["key1"];
$val2 = $_POST["key2"];
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment