Source code user service

What is the correct JSON content type?

If you are in a process of making custom web application and you need to send some data to the client, it may be necessary to set proper media type for the content.

This is usually a case when you have to transmit arrays, objects, or any sort of attribute-value pairs of data.

As result, the correct content type for the JSON text will be:

application/json

Also, it's important to note that the correct content type for JSONP (JSON with Padding) is below:

application/javascript

JSON stands for JavaScript Object Notation. This is a very popular and common format and it's widely used in web development. It's lightweight, interchangeable and language independent and it can contain almost any type of data, such as variables, arrays, objects, etc. This means that you can easily create JSON string in JavaScript and later parse and read it, for example, in PHP.

On another side, JSON-P is a technology that allows to load data from a remote server via the <script> tag. It was created to solve issue with cross domain access, which is usually not allowed. For example, your code is running on example.com domain and you need to access data on example.net domain. Then, you would need to create some callback and run code on the second server. In such a scenario, the URL may be like this:

https://example.net/sample?callback=datacallback

Then, in your code, the <script> tag can look like the following:

<script type="application/javascript"
     src="https://example.net/sample?callback=dataCallBack">
</script>

The server side may want to return some JavaScript object. It can be anything, but only for this example, we assume it's a simple product:

{
    "Product": "computer",
    "Id": 12345,
    "Price": 249.99
}

Then, your callback may be invoked with the data passed as an argument:

dataCallBack({"Product": "computer", "Id": 12345, "Price": 249.99 });

Although, this is not a standard way of making web applications and there are some drawbacks of using it, like error handling. Your script may not be able to handle non-standard situations that can occur on the server side.

But there is another option, you may consider using Cross-Origin Resource Sharing (CORS) technology instead of the JSON-P.

With help of CORS, you can specify domains which are allowed to load resources from the target, and browsers will do a check before processing a request to it.

In our specific example, the second server may have the following setting in HTTP response headers:

Access-Control-Allow-Origin: https://example.com

Also, you can replace the above rule with a wildcard setting to make the server less restrictive and to allow access from any domain, but this is not a preferred method, see how it will look:

Access-Control-Allow-Origin: *

How to set content type in PHP

You can send content type in PHP with help of the header() function. It accepts only three parameters, the full descriptions is as the following:

 header ( string $header , bool $replace = true , int $response_code = 0 ) : void

$header - you can specify content type in this variable, or set a status code.

$replace - whether the header should replace previous variable or the header must be added to the existing one

$response_code - set response code to the specified value.

Here you can see a typical example of how to send content type for the JSON in PHP:

<?php
header('Content-Type: application/json');
?>

How to set content type in NodeJS

There are different ways to set the content type in Node.js application, for example, you can use writeHead() function from the http.ServerResponse class, see our code example:

const server = http.createServer((request, response) => {
    response.writeHead(200, { 'Content-Type': 'application/json' });
});

In the demo above, we created a very simple server that issues a 200 status code with the content type of 'application/json'. The next step would be to send some data to the client, and of course, it's for you to decide how to extend such a simple script.

The writeHead() function accepts three parameters. As you already noticed, the first one is a status code and it's mandatory. Second parameter is a status message, and the third is a list of headers. Here is the full function definition:

response.writeHead(statusCode[, statusMessage][, headers])

The other option to set content type in Node.js application is by using setHeader() function, see how it looks below:

response.setHeader(name, value);

You need to pass header name and value here. If this header already exists, it's value will be replaced by the new one.

response.setHeader('Content-Type', 'application/json');

The main difference between writeHead() and setHeader() functions is that you can specify multiple headers with the first one, but with the second function, you can set single header only.

Related Articles

Test cases in web application

Check if a string contains a substring in JavaScript

Javascript array mapping

Remove specific item from an array in JavaScript

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *