mdikici
mdikici

Reputation: 1504

node.js POST request

I looked at the api but I couldn't find it.

Where/How should I put data on a POST request on client.request() or client.request("POST" ,...)?

Upvotes: 5

Views: 11021

Answers (3)

ranm8
ranm8

Reputation: 1093

You can also use Requestify, a really cool and very simple HTTP client I wrote for nodeJS + it supports caching.

Just do the following for executing a POST request:

var requestify = require('requestify');

requestify.post('http://example.com', {
    hello: 'world'
})
.then(function(response) {
    // Get the response body (JSON parsed or jQuery object for XMLs)
    response.getBody();
});

Upvotes: 0

Farid Nouri Neshat
Farid Nouri Neshat

Reputation: 30430

For more easier client requests you can use request module. It takes care of all the hard work and has a simple API.

Upvotes: 1

selfawaresoup
selfawaresoup

Reputation: 15832

Maybe you should look closer then.

This is straight from the node.js API documentation:

request_headers is optional. Additional request headers might be added internally by Node. Returns a ClientRequest object.

Do remember to include the Content-Length header if you plan on sending a body. If you plan on streaming the body, perhaps set Transfer-Encoding: chunked.

NOTE: the request is not complete. This method only sends the header of the request. One needs to call request.end() to finalize the request and retrieve the response. (This sounds convoluted but it provides a chance for the user to stream a body to the server with request.write().)

request.write() is for sending data.

So you do it like this (more or less):

var rq = client.request('POST', 'http://example.org/', {'Content-Length': '1024'});
var body = getMe1024BytesOfData();

rq.write(body);
rq.end();

This code is just here to get the concept across. I have NOT tested it in any way.

Upvotes: 8

Related Questions