npm request set body - node.js

When using request, how do you set the request body? The form parameter creates a body of key value pairs: foo=bar&baz=qux, but how do you set the body to an arbitrary string?

You can set request body in the options params.
const options = {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({test: 1});
};
request(options, function (err, res, body) {
// handle err or use response and response boy
});
Depending upon the content you want to send, you can provide the string needed.

Related

Why am I getting an empty body as response from HTTP request Noe.js

so I am trying to send a http request to a server and as response I should get the body where all the information I need is in. When I then try to .parseJSON() the body I get an exception telling me that my body is empty. There is no way that the body is really empty so there has to be a mistake in the code.
I can not give you the whole code because of passwords and stuff like that.
Code:
public addVehicle(): Promise<void>{
return new Promise<void>((resolve, reject) => {
const options = {
url: [URL],
method: "POST",
headers: {
'Content-Type': 'application/json',
'Authorization': [user/psw],
'token': [authToken]
},
body: JSON.stringify({
'vehicleID': vehicleID,
'externalID': externalID,
'brandID': vehicleBrandId,
'modelGroupID': vehicleModelId,
'typeName': typeName,
'segmentationID': vehicleSegmentationId,
'categoryID': vehicleCategoryId,
'fuelTypeID': vehicleFuelTypeId,
'transmissionTypeID': vehicleTransmissionTypeId,
'propulsionTypeID': vehiclePropulsionTypeId,
'registerationDate': registerationDate,
'powerKW': powerKW,
'description': description
})
}
let req = request.post(options, (err, res, body) => {
let rawAuth = JSON.parse(body);
console.log(body);
resolve();
})
})
}
Try removing the JSON.stringify().
I am assuming that your receiving API expects the fields in the body. Sending the data as string will hide the fields from the receiving API. It will just see one string object (not sure what the key will be tho).
const options = {
url: [URL],
method: "POST",
headers: {
'Content-Type': 'application/json',
'Authorization': [user/psw],
'token': [authToken]
},
body: {
'vehicleID': vehicleID,
'externalID': externalID,
'brandID': vehicleBrandId,
'modelGroupID': vehicleModelId,
'typeName': typeName,
'segmentationID': vehicleSegmentationId,
'categoryID': vehicleCategoryId,
'fuelTypeID': vehicleFuelTypeId,
'transmissionTypeID': vehicleTransmissionTypeId,
'propulsionTypeID': vehiclePropulsionTypeId,
'registerationDate': registerationDate,
'powerKW': powerKW,
'description': description
}
}

Using request module and passing the body to the next request

I am using request to get an image:
request(req.body.imageUrl, {encoding: null}, function(error, response, body) {
I then want to use the body to pass to an api that uses a multipart form and send that image (which is now in the body). I don't want to write the file to disk and then readstream from the disk again. I basically want to enter the formData of the next request by using the Buffer of the body, but it is not working.
So, for the options in the next request I have:
const options = {
method: "POST",
url: coreURL,
headers: {
"Content-Type": "multipart/form-data"
},
formData : {
file : new Buffer.from(body,'binary')
}
};
And this does not work, if I write the body to a file fs.writeFileSync(fileName, body, 'binary');
And then read in the options formData : { file : fs.createReadStream(fileName)}
it works but I cannot use the disk, so need an alternative way to pass the body into the next post as multipart form data.
Any ideas?
POC:
let request = require('request');
request.post({
url: "http://httpbin.org/anything",
formData: {
myfile: request.get("https://www.gravatar.com/avatar/f056d36f9e273fd4740ec8a5cea1348a"),
}
},
function (err, req, body) {
console.log(body);
}
);

The request body must contain the following parameter: 'grant_type'... but I put it in the body

I put the grant_type parameter in the request body as the documentation shows, but Microsoft Graph still complains that it's not there;
const tokenRequestBody = [
"grant_type=client_credentials",
"scope=https%3A%2F%2Fgraph.microsoft.com%2F.default",
`client_secret=${config.appClient.password}`
].join("&");
request.post(
{
url: tokenRequestUrl,
json: true,
headers: {
"content-type": "application/application/x-www-form-urlencoded"
},
body: tokenRequestBody
},
(err, req, body) => {
console.log(body.error_description);
// Logs: The request body must contain the following parameter: 'grant_type'.
}
);
I figured it out. I had to use form instead of body for the request node module.

How to view request sent from node.js to server?

Regarding to this question:
Transfer / pass cookies from one request to another in nodejs/protractor
I got another one. How could I view complete request (headers + body) which I am performing via nodejs?
Yes, you can ... You can access the complete request from the full response body - response.request
I have a generic full response structure illustrated below
IncomingMessage
ReadableState
headers(ResponseHeaders)
rawHeaders
request - //This is what you need
headers
body
body(Response Body)
You can access through code as shown below
var request = require("request");
var options = { method: 'POST',
url: 'http://1.1.1.1/login',
headers:
{ 'cache-control': 'no-cache',
'content-type': 'application/json' },
body: { email: 'junk#junk.com', password: 'junk#123' },
json: true };
request(options, function (error, response, body) {
if (error) throw new Error(error);
// This will give you complete request
console.log(response.request);
//This gives you the headers from Request
console.log(response.request.headers);
});

request node.js module can't send a simple POST

I send it like so :
var url = "http://localhost:9001/v1/sanger/auth/facebook/callback",
options = {body: JSON.stringify(params), 'Content-type': 'application/json'};
request.post(url, options, function (error, response, body) {
... callbacks ...
});
I am not getting the params in the route (tried body, params and query)
When I use postman (http://cl.ly/image/473e2m173M2v) I get it in the req.body
A better way to do this (I'm assuming you've initialized your params variable somewhere else):
request = require('request');
var options = {
url: "http://localhost:9001/v1/sanger/auth/facebook/callback",
method: 'POST',
body: params,
json: true
};
request(options, function (error, response, body) {
... callbacks ...
});
You're not able to get the body because when you call JSON.stringify(params), you're converting params to a string and you don't have a json object anymore. If you send the information as plain/text but tell the request that you want json, your express app cannot verify the content-type, as could check with:
request.get('Content-Type'); // returns undefined
Since you want a json object, you shouldn't do this. Just pass the json object, like in the example above.
Then, in your route code, you can do both req.body or req.param('a_param') (for a especific key of your json) to get those values.

Resources