Orlando Orlando - 1 year ago 197
Javascript Question

curl -d equivalent in Node.js http post request

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) {
request.on('error', function(err) {
console.log("An error ocurred!");


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!

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download