How to post to a request using node.js

泪湿孤枕 提交于 2019-12-02 15:49:24

The issue is that you are setting Content-Type in the wrong place. It is part of the request headers, which have their own key in the options object, the first parameter of the request() method. Here's an implementation using ClientRequest() for a one-time transaction (you can keep createClient() if you need to make multiple connections to the same server):

var http = require('http')

var body = JSON.stringify({
    foo: "bar"
})

var request = new http.ClientRequest({
    hostname: "SERVER_NAME",
    port: 80,
    path: "/get_stuff",
    method: "POST",
    headers: {
        "Content-Type": "application/json",
        "Content-Length": Buffer.byteLength(body)
    }
})

request.end(body)

The rest of the code in the question is correct (request.on() and below).

Jonathan O'Connor

Jammus got this right. If the Content-Length header is not set, then the body will contain some kind of length at the start and a 0 at the end.

So when I was sending from Node:

{"email":"joe@bloggs.com","passwd":"123456"}

my rails server was receiving:

"2b {"email":"joe@bloggs.com","passwd":"123456"} 0  "

Rails didn't understand the 2b, so it wouldn't interpret the results.

So, for passing params via JSON, set the Content-Type to application/json, and always give the Content-Length.

To send JSON as POST to an external API with NodeJS... (and "http" module)

var http = require('http');

var post_req  = null,
    post_data = '{"login":"toto","password":"okay","duration":"9999"}';

var post_options = {
    hostname: '192.168.1.1',
    port    : '8080',
    path    : '/web/authenticate',
    method  : 'POST',
    headers : {
        'Content-Type': 'application/json',
        'Cache-Control': 'no-cache',
        'Content-Length': post_data.length
    }
};

post_req = http.request(post_options, function (res) {
    console.log('STATUS: ' + res.statusCode);
    console.log('HEADERS: ' + JSON.stringify(res.headers));
    res.setEncoding('utf8');
    res.on('data', function (chunk) {
        console.log('Response: ', chunk);
    });
});

post_req.on('error', function(e) {
    console.log('problem with request: ' + e.message);
});

post_req.write(post_data);
post_req.end();

There is a very good library that support sending POST request in Nodejs:

Link: https://github.com/mikeal/request

Sample code:

var request = require('request');

//test data
var USER_DATA = {
    "email": "email@mail.com",
    "password": "a075d17f3d453073853f813838c15b8023b8c487038436354fe599c3942e1f95"
}

var options = {
    method: 'POST',
    url: 'URL:PORT/PATH',
    headers: {
        'Content-Type': 'application/json'
    },
    json: USER_DATA

};


function callback(error, response, body) {
    if (!error) {
        var info = JSON.parse(JSON.stringify(body));
        console.log(info);
    }
    else {
        console.log('Error happened: '+ error);
    }
}

//send request
request(options, callback);

Try including the content length.

var body = JSON.stringify(some_json);
var request = google.request('POST', '/get_stuff', { 
    host: 'server',
    'Content-Length': Buffer.byteLength(body),
    'Content-Type': 'application/json' 
    });
request.write(body);
request.end();

This might not solve your problem, but javascript doesn't support named arguments, so where you say:

request.write(JSON.stringify(some_json),encoding='utf8');

You should be saying:

request.write(JSON.stringify(some_json),'utf8');

The encoding= is assigning to a global variable, so it's valid syntax but probably not doing what you intend.

Probably non-existent at the time this question was asked, you could use nowadays a higher level library for handling http requests, such as https://github.com/mikeal/request. Node's built-in http module is too low level for beginners to start with.

Mikeal's request module has built-in support for directly handling JSON (see the documentation, especially https://github.com/mikeal/request#requestoptions-callback).

Jasper Fu
var request = google.request(
  'POST',
  '/get_stuff',
  {
    'host': 'sever',
    **'headers'**:
    {
      'content-type': 'application/json'
    }
  }
);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!