Mohsen Shakiba
Mohsen Shakiba

Reputation: 1872

Javascript & Node.js - make a JSON request

in this Question I read that in node.js you can distinguish between html requests and json requests like so:

app.get('/route', function (req, res) {
    if (req.is('json')) res.json(data);
    else if (req.is('html')) res.render('view', {});
    else ...
});

now my question is how do you make a request that is interpreted as json in node server?
cause I tried with $.ajax and $.getJson and typed in the browser and all were html requests.
this is my request

$.ajax({ type: 'GET', url: "/test", dataType:"json", success: function(data){log(data)}})

Upvotes: 0

Views: 78

Answers (2)

James
James

Reputation: 82096

The req.is method checks the incoming request type by inspecting the Content-Type header therefore you need to make sure this header is set in the request before it's sent up e.g.

$.ajax({
    type: 'GET',
    url: '/route',
    contentType: "application/json; charset=utf-8",
    ....
});

However, the Content-Type header is used to determine the format of the request body, not the response. It's recommended you use the Accept header instead to inform the server of what type of format is appropriate for the response e.g.

app.get('/route', function (req, res) {
    if (req.accepts('html')) {
        res.render('view', {});
    } else if (req.accepts('json')) {
        res.json(data);
    } else {
        ...
    }
});

Then on the client, you don't need to worry about the Content-header but rather the Accept header, and jQuery already provides a handy little method for that

$.getJSON('/route', function(data) {
    ...
});

Upvotes: 3

Abhinav
Abhinav

Reputation: 8168

Try setting the contentType parameter

$.ajax({
    type: 'GET',
    url: 'your_url',
    data: {
        test: "test"
    },
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    ....
});

EDIT:

You can use the request Module all you have to do is

var request = require('request');

var options = {
  uri: 'your_server_side_url',
  method: 'POST',
  json: {
    "data": "some_data"
  }
};

request(options, function (error, response, body) {
  if (!error && response.statusCode == 200) {
    console.log(body.id) // Print the shortened url.
  }
});

Check out that github link. May be that module will make your life easier

Upvotes: 1

Related Questions