Question

I know that the command

curl -X POST -d 'some data to send' http://somehost.com/api 

can be emulated in Node.js with some code like

var http = require('http');
var post_data = 'some data to send',
    headers = {
        host: 'somehost.com',
        port: 80,
        method: 'POST',
        path: '/api',
        headers: {
            'Content-Length': Buffer.byteLength(post_data)
        }
    };

var request = http.request(headers, function(response) {
    response.on('data', function(d) {
        console.log(d);
    });
});
request.on('error', function(err) {
    console.log("An error ocurred!");
});
request.write(post_data));

request.end();

The question is because I'm looking for the equivalent in node of the cURL command

curl -d name="Myname" -d email="myemail@gmail.com" -X POST http://somehost.com/api

how can i do that?

This is because I wanna do a POST request to a Cherrypy server like this one, and I'm not able to complete the request.

EDIT The solution, as @mscdex said, was with the request library:

I've resolve the problem with the request library. My code for the solution is

var request = require('request');

request.post('http://localhost:8080/api', {
  form: {
    nombre: 'orlando'
  }
}, function(err, res) {
  console.log(err, res);
});

Thank you!

Was it helpful?

Solution

You could encode it manually:

var post_data = 'name=Myname&email=myemail@gmail.com';

Or you could use a module like request to handle it for you (becomes especially nice if you have to upload files) since it will handle data escaping and other things for you.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top