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

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.

Related

How to select specific field of a JSON response in Node JS?

I have the following API response named "body" and trying to log a specific field/submap, for example the "response" map. I don't really know the correct syntax in NodeJS or JavaScript.
{"get":"fixtures","parameters":{"league":"135","season":"2022","status":"NS","timezone":"Europe\/rome"},"errors":[],"results":40,"paging":{"current":1,"total":1},"response":[{"fixture":{"id":881790,"referee":"M. Piccinini","timezone":"Europe\/rome","date":"2022-08-20T18:30:00+02:00","timestamp":1661013000,"periods":{"first":null,"second":null},"venue":{"id":943,"name":"Stadio Olimpico Grande Torino","city":"Torino"},"status":{"long":"Not Started","short":"NS","elapsed":null}},"league":{"id":135,"name":"Serie A","country":"Italy","logo":"https:\/\/media.api-sports.io\/football\/leagues\/135.png","flag":"https:\/\/media.api-sports.io\/flags\/it.svg","season":2022,"round":"Regular Season - 2"},"teams":{"home":{"id":503,"name":"Torino","logo":"https:\/\/media.api-sports.io\/football\/teams\/503.png","winner":null},"away":{"id":487,"name":"Lazio","logo":"https:\/\/media.api-sports.io\/football\/teams\/487.png","winner":null}},"goals":{"home":null,"away":null},"score":{"halftime":{"home":null,"away":null},"fulltime":{"home":null,"away":null},"extratime":{"home":null,"away":null},"penalty":{"home":null,"away":null}}},]}
The code is below:
var request = require("request");
var options = {
method: 'GET',
url: 'https://v3.football.api-sports.io/fixtures?league=135&season=2022&status=NS&timezone=Europe/rome',
qs: {},
headers: {
'x-rapidapi-host': 'v3.football.api-sports.io',
'x-rapidapi-key': 'xxxxxxxxxxxxxxxxx'
}
};
request(options, function (error, response, body) {
if (error) throw new Error(error);
console.log(body);
});
I tried console.log(body.response); without success. I also tried body["response"] ending with "undefined" result.
It seems body was a String result so I could select the field with JSON syntax. I solved with console.log(JSON.parse(body).response[0]);
Two approaches:
Approach 1: Set the Content-Type as application/json in the server.
Approach 2: Convert the body from string to JSON object by JSON.parse

Node JS request get original url

I'm sending GET requests like this in Node JS in a loop
request({
url : 'https://somelink.com',
method: 'GET'
},
function (error, response, body) {
console.log(response);
});
Since the response is async, is it possible to get the original request URL in the response?
Thanks!
You can get the original request href in the response.request object, like so:
const request = require("request");
request({
url : 'https://google.com',
method: 'GET'
},
function (error, response, body) {
if (!error) {
console.log("Original url:", response.request.uri.href);
console.log("Original uri object:", response.request.uri);
}
});
You can access more information in the request.uri object, for example:
console.log("Original uri:", response.request.uri);
This will give you some more useful information like port, path, host etc.

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);
}
);

Send unparsed data in a Node JS request

I want to send a POST request (for example, with the 'request' module), but I don't find a way of sending unparsed data*.
*unparsed data => copied directly from the Chrome dev tool. Something like: tipo_accion=3&filtro=descarga&fecha=actual
It would also do the trick some way of translating that string to JSON.
I've tried so far with...
var request = require('request');
request.post({ url: 'https://target.com/form/', form: 'tipo_accion=3&filtro=descarga&fecha=actual' },
function (error, response, body) {
console.log(body)
}
);
... but it didn't work.
Firstly you should understand the difference between the request methods post and get.
The structure that you want to send:
tipo_accion=3&filtro=descarga&fecha=actual is telling me that you want to use a get request. So the proper code for that will be something like:
request(
'https://target.com/form/&tipo_accion=3&filtro=descarga&fecha=actual',
function (error, response, body) {
console.log(body)
},
);
But if it is a post request then you should use the json format
request.post({
url: 'https://target.com/form/', form: {
tipo_accion: 3,
filtro: 'descarga',
fecha: 'actual'
},
function(error, response, body) {
console.log(body)
}
);
You can convert form_data to string format and it works for me you can try it :
const request = require('request-promise');
var j = request.jar()
var data_fom = `a=value_a&b=value_b&c=value_c`
request({
url:"https://target.com/form/",
jar:j,
method:"POST",
resolveWithFullResponse: true,
form:data_form
})

calling external rest api from node without encoding querystring params

I am trying to call an external rest API from node server by using request node module.
let request = require('request');
var options = {
method: 'POST',
url: 'https://somerestURI:3000',
qs: { msg: 'some|data|for|other|server' }
};
request(options, function (error, response, body) {
if (error) throw new Error(error);
console.log(body);
});
If I try to run the above code, query string value is being encoded to
some%7cdata%7cfor%7cother%7cserver
as a result I am not receiving correct response.
But if I fire the same request in POSTMAN. I am receiving the expected output(I think postman is not encoding query string).
So what I want is don't encode the query string value.
Any help would be greatly appreciated.
As answered here, you can disable encoding in qsStringifyOptions
var options = {
method: 'POST',
url: 'https://somerestURI:3000',
qs: { msg: 'some|data|for|other|server' },
qsStringifyOptions: {
encoding: false
}
};
You can use node-rest-client package. It allows connecting to any REST API and get results as javascript Object.
var HttpClient = require('node-rest-client').Client;
var httpClient = new HttpClient();
// GET Call
httpClient.get("http://remote.site/rest/xml/method", function (data, response) {
// parsed response body as js object
console.log(data);
// raw response
console.log(response);
});)
or for POST Call
var args = {
data: { test: "hello" },
headers: { "Content-Type": "application/json" }
};
//POST Call
httpClient.post("http://remote.site/rest/xml/method", args, function (data, response) {
// parsed response body as js object
console.log(data);
// raw response
console.log(response);
});

Resources