Linus Odenring
Linus Odenring

Reputation: 881

Trying to post api request

I having problem with making a API call to an external site.

I need to send a POST request to http://api.turfgame.com/v4/users with headers Content-type: application/js. But when I run this code it only loads and nothing more.

var request = require('request');

    var options = {
        uri: 'http://api.turfgame.com/v4/users',
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: {
            "name": "username"
        }
    };

    request(options, function (error, response, body) {
        if (!error && response.statusCode == 200) {
             res.send(response.body);
        }
});

The body need to be posted in json formate [{'name': 'username'}].

Can someone tell me what I have done wrong?

Upvotes: 0

Views: 68

Answers (1)

Chris
Chris

Reputation: 23171

There are a few things wrong:

  • the address property in the "options" object should be "url" not "uri"
  • you can use the "json" property instead of body
  • "res" is undefined in your response handler function
  • if you want the body to be an array, it needs to be surrounded in square brackets

here's a working sample that just logs the response:

var request = require('request');

    var options = {
        url: 'http://api.turfgame.com/v4/users',
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        json: [{
            "name": "username"
        }]
    };

    request(options, function (error, response, body) {
        if (!error && response.statusCode == 200) {
             console.log(response.body);
        }
});

Upvotes: 1

Related Questions