WilliamG
WilliamG

Reputation: 491

POST request node js

Okay so I have struggled with this for quite a while. I have a curl command that are supposed to work. Since I'm not familiar with curl I "translated" it to node. But it doesn't work. Here is the curl line.

    curl -X POST --header 'Content-Type: application/json' --header 'token: XXXXXX' -d '[ \ 
   { \ 
     "id": "eh", \ 
     \ 
     "kind": "goods", \ 
     "data": {} \ 
   } \ 
 ]' 'http://localhost:5000/api/article'

When I have translated it to node it looks like this:

var request = require('request');

var dataString = '[ \ 
   { \ 
     "id": "eh", \ 
     \ 
     "kind": "goods", \ 
     "data": {} \ 
   } \ 
 ]';

var options = {
    url: 'http://localhost:5000/api/article',
    method: 'POST',
    body: dataString
};

function callback(error, response, body) {
    if (!error && response.statusCode == 200) {
        console.log(body);
    }
}

request(options, callback);

The error message I get is

throw new TypeError('First argument must be a string or Buffer');

Can someone tell me what is wrong? Thanks

Upvotes: 0

Views: 560

Answers (2)

pietrovismara
pietrovismara

Reputation: 6291

From request docs:

body - entity body for PATCH, POST and PUT requests. Must be a Buffer, String or ReadStream. If json is true, then body must be a JSON-serializable object.

So you have two options here.

If this is the body you want to send:

var data = [{
    "id": "eh",
    "kind": "goods",
    "data": {}
}];

You can do pass the json: true option:

var options = {
    url: 'http://localhost:5000/api/article',
    method: 'POST',
    body: data,
    json: true
};

Or you can stringify your data array before sending it:

var options = {
    url: 'http://localhost:5000/api/article',
    method: 'POST',
    body: JSON.stringify(data)    
};

Upvotes: 2

Love-Kesh
Love-Kesh

Reputation: 812

var dataString = [  
   { 
     "id": "eh",  
     "kind": "goods", 
     "data": {} 
   } 
 ];

var options = {
    url: 'http://localhost:5000/api/article',
    method: 'POST',
    body: dataString
};

function callback(error, response, body) {
    if (!error && response.statusCode == 200) {
        console.log(body);
    }
}

//request(options, callback);
enter code here
 request.post({url:options.url, formData: :options.body}, callback);

Upvotes: 0

Related Questions