4

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="[email protected]" -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!

1 Answer 1

6

You could encode it manually:

var post_data = 'name=Myname&[email protected]';

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.

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

1 Comment

You're right. I've resolve the problem with the request library. My code for the solution is var request = require('request'); request.post('localhost:8080/api', { form: { nombre: 'orlando' } }, function(err, res) { console.log(err, res); }); Thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.