How to Set Params with Node Get Request - node.js

I am trying to make a get request using the NPM Request module and am having trouble passing in a params argument.
Going through the docs I can't tell what the correct syntax is.
makeRequest(req, res, num, cookie) {
request({
headers: {
'Cookie': cookie
},
url: 'https://api.domain.com/path',
params: num // this is incorrect
},
(error, response, body) => {
res.json({
msg: "Success"
})
}
})
}
How can I pass a params argument into a request?

https://www.npmjs.com/package/request
qs - object containing querystring values to be appended to the uri
request({
headers: {
'Cookie': cookie
},
url: 'https://api.domain.com/path',
qs: { num: 1}
})
This should create a url
https://api.domain.com/path?num=1

Related

Writing an if statement in axios setting URL

I want to write an if statement in axios setting URL config to check if the method is post do not send the params but I get syntax error.
Something like code below
if (method = 'GET') {
params: req.params,
},
Code without if statement that works fine:
axios({
url: API_URL + req.url,
method: req.method,
params: req.params,
data: req.body,
if (body) {
}
})
Assuming that params needs to be passed optional [from question: check if the method is post do not send the params] in the below code-sample:
axios({
url: API_URL + req.url,
method: req.method,
params: req.params, // make this optional based on method != POST
data: req.body,
})
Please try something like this:
axios({
url: API_URL + req.url,
method: req.method,
data: req.body,
...(
(req.method !== 'POST')
? { params: req.params }
: {}
)
});

Request Module returning null for google API

I was trying Gmail APIs. Using POSTMAN I have created oAuth 2.0 token and was able to hit the URL https://www.googleapis.com/gmail/v1/users/xyz#gmail.com/profile. But when I was trying same with my node project where I invoked the same using :
app.get('/getMail',getMail); in my index.js where getMail is as follows
exports.getMail = (req, res) => {
request({
url: "https://www.googleapis.com/gmail/v1/users/xyz#gmail.com/profile",
method: "GET",
headers: {
Authorization: 'Bearer token'
},
json: true
}, function(response) {
console.log(JSON.stringify(response, null, 4));
return res.json(response);
});
But I am getting the response as null. Any help would be appreciated.
Please change the callback function to include error. The callbacks are usually error-first callbacks meaning first argument is always error.
exports.getMail = (req, res) => {
request({
url: "https://www.googleapis.com/gmail/v1/users/xyz#gmail.com/profile",
method: "GET",
headers: {
Authorization: 'Bearer token'
},
json: true
// Here -> error
}, function(error, response) {
if (error) throw new Error(error); // Handle the error here.
console.log(JSON.stringify(response, null, 4));
return res.json(response);
});

How to add headers in superagent GET request

Here is a basic code:
const superagent = require('superagent');
superagent.get('https://api.arabam.com/pp/step')
.query({ apikey: '_V85Kref7xGZHc1XRpUmOhDDd07zhZTOvUSIbJe_sSNHSDV79EjODA==' })
.end((err, res) => {
if (err) { return console.log(err); }
console.log(res.body.url);
console.log(res.body.explanation);
});
But apikey is header rather than query. How do I send it as a header?
Edit:
I have tried using request module and it simply says that I'm unable to access it
var request = require("request");
request({
uri: "https://api.arabam.com/pp/step",
method: "GET",
'Content-Type' : "application/json",
apikey: "_V85Kref7xGZHc1XRpUmOhDDd07zhZTOvUSIbJe_sSNHSDV79EjODA=="
}, function(error, response, body) {
console.log(body);
});
It says unauthorized to access
From the Setting header fields doc, you should use
request.set('apikey', '_V85Kref7xGZHc1XRpUmOhDDd07zhZTOvUSIbJe_sSNHSDV79EjODA==')
to set the header field.

CSRF token validation failed in nodejs while posting data to odata service

var request = require('request');
var username = '';
var password = '';
var url = 'http://207.188.73.88:8000/sap/opu/odata/sap/ZTEE_TIME_SRV/ZTEERESERVESet(Time=time\'PT11H00M00S\',Date=datetime\'2014-03-11T00%3A00%3A00\',Location=\'TAJ\',Number=3)';
var auth = 'Basic ' + new Buffer(username + ':' + password).toString('base64');
// i am trying to post data to odata service but the problem is that i could not get valid token from get service to use it in the post method i am first send get method
request(
{
url: url,
headers: {
'Authorization': auth,
'x-csrf-token': 'Fetch',
},
},
function(error, response, body) {
console.log('JSON data ' + response);
console.log('body' + body);
// trying to get the token to use in post
console.log(response.headers);
request(
{
url: url,
headers: {
here it says invalid token
'Authorization': auth,
'X-CSRF-TOKEN': 'u6piLO58XoK6udOkQ5Naww==',
},
method: 'POST',
//Lets post the following key/values as form
form: {
Time: 'PT11H00M00S',
Date: '2014-03-11T00%3A00%3A00',
Location: 'TAJ',
Number: 3,
},
},
function(error, response, body) {
console.log(body);
},
);
},
);
I got the solution.
I was trying to do this with POSTMAN, and it was working fine.
The thing is that when i was asking for CSRF token it always gave me the same back.
But when i tried with node, every time was different. Then i realized that the cookie was missing.
And thats all, the solution is to send the cookie at least in POST requests.
The set-cookie of the "Fetch" request must be sent in the Post request as Cookie beside the x-csrf-token
I put the example in typescript, but in js doesnt change so much, the idea is the same.
The example is not the best case but is complete to figure out how it works
let headers = {
"Authorization": "Basic " + new Buffer(username + ":" + password).toString("base64"),
"Content-Type":"application/json",
"Accept":"application/json",
"x-csrf-token":"Fetch" // get CSRF Token for post or update
};
// if you are using session vars
if (req.session.headers && req.session.headers.cookie) {
headers['Cookie'] = req.session.headers.cookie;
} else {
req.session.headers = {}; // initialize as object
}
let opts = {
url: "https://{host}:{port}/sap/opu/odata/sap/MD_SUPPLIER_MASTER_SRV",
qs: params1, // params set before, not set in the example
headers: headers,
json: true,
}
request(opts, (error: any, response: any, body: any): any => {
if (!error && response.statusCode === 200) {
if (response.headers["set-cookie"]) {
req.session.headers.cookie = response.headers["set-cookie"]; // store Cookie in session
headers['Cookie'] = req.session.headers.cookie; // set in headers for the next call. I guess this is the part you missed
}
if (response.headers['x-csrf-token']) {
req.session.headers.csrf = response.headers['x-csrf-token']; // store csrf-token in session
headers['x-csrf-token'] = req.session.headers.csrf; // set in headers for the next call
}
let options: request.Options = {
url: "https://{host}:{port}/sap/opu/odata/sap/MD_SUPPLIER_MASTER_SRV/C_BusinessPartnerSupplierEdit",
method: 'POST',
headers: headers,
qs: params2, // params set before
json: true,
}
request(options, (error: any, response: any, body: any): any => {
res.json(body);
});
}
});
Regards

use GET method in node js request?

i want to pass data with GET method in node js , my response is ok but in php file $_GET is empty. what is wrong?
var querystring = require('querystring');
var req = require('request');
var form = {
number: 'test',
msg: 'test',
};
var formData = querystring.stringify(form);
var contentLength = formData.length;
req({
headers: {
'Content-Length': contentLength,
'Content-Type': 'application/x-www-form-urlencoded'
},
uri: 'http://localhost:8080/sms/index.php',
body: formData,
method: 'GET'
}, function (err, res, body) {
console.log('res is',res);
console.log('err',err);
});
An HTTP GET request cannot have a request body. $_GET parses parameters from the query string. The headers Content-Lengthand Content-Type do not make sense for a GET request as they apply to the body of the request, which GET cannot have. You need to use the qs option instead of body.
req({
uri: 'http://localhost:8080/sms/index.php',
qs: form,
method: 'GET'
}, function (err, res, body) {
//
});

Resources