hypervillain
hypervillain

Reputation: 393

Converting cURL request for node js using Request

This is a simple one I guess : I would like to make a request on a Node.js server as I'm currently doing it with cURL. Whatever I try, I get an error 404 from the server.

Here is my valid cURL command which returns a JavaScript object:

curl --data "ajax=1&example=test" http://some-site-example.com

After reading cURL manual and Request manual, here is what I tried in Node.js:

request.post({'content-type':'application/x-www-form-urlencoded',ajax:'1',example:'test',url:'http://some-site-example.com'}, function(err, result, body) {
    if (err) console.log(err);    
    else console.log(body);
});

Upvotes: 0

Views: 1535

Answers (2)

Michael
Michael

Reputation: 1322

This should do it, form automatically adds the content-type, here's the manual:

request.post('http://some-site-example.com', {form: {ajax:'1',example:'test'}}, function(err, result, body) {
    if (err) console.log(err);    
    else console.log(body);
});

Upvotes: 0

mscdex
mscdex

Reputation: 106706

Your options are wrong for a application/x-www-form-urlencoded form. Also, by specifying form, it automatically sets the correct Content-Type. So try this:

request.post({form: {ajax:'1', example:'test'}, url: 'http://some-site-example.com'}, function(err, response, body) {

instead of:

request.post({'content-type':'application/x-www-form-urlencoded',ajax:'1',example:'test',url:'http://some-site-example.com'}, function(err, result, body) {

Upvotes: 1

Related Questions