5

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" ,...)?

3 Answers 3

8

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.

Sign up to request clarification or add additional context in comments.

3 Comments

you can also do rq.end(body) if that suits your style better
True, but I like to keep things with different purposes apart: write() is for output and end() is for ... well ... ending.
This seems to have changed in v0.3.6. and seems much different now in v0.4.7
1

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

Comments

0

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();
});

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.