Writing an if statement in axios setting URL - node.js

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

Related

Axios bad request status 400

I'm having this issue AxiosError: Request failed with status code 400
I checked the console and I test manually the url and It worked, so I don't know what's wrong, this code:
//file controller.js
//Set Create Session
exports.setSession = async (req, res) => {
const data = await request({
path: process.env.APP_LOCALHOST_URL + urlLogin.setCreateSession,
method: 'POST',
body: JSON.stringify(req.body)
});
return res.json(data);
}
//file request.js
exports.request = async ({path, method = "GET", body }) => {
try {
const response = await axios({
method: method,
url: path,
headers: {
'Content-Type': 'application/json'
},
body: body
});
return response;
} catch (error) {
console.log("error: ", error);
}
}
the function setSession is to call in my routes file, and the function request is my reusable component. My intention is to use the function request in many functions, these could be of the GET, DELETE, PUT, POST, PATCH type.
So, currently I get this on console:
data: {
error: '5',
errorId: 'badRequest',
errorString: 'Internal error: Undefined JSON value.'
}

How to Set Params with Node Get Request

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

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

Async request module in Node.js

I am creating a project using Node.js. I want to call my requests in parallel. For achieving this, I have installed the async module. Here is my code:
var requests = [{
url:url,
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + req.cookies.apitoken
},
json: finalArr,
}];
async.map(requests, function(obj, callback) {
// Iterator function
request(obj, function(error, response, body) {
if (!error && response.statusCode == 200) {
// Transform data here or pass it on
var body = JSON.parse(body);
callback(null, body);
}
else {
var body = JSON.stringify(body);
console.log(body)
callback(error || response.statusCode);
}
});
})
I got undefined every time in console.log(body). When I am using GET requests using this module for other requests then everything works fine.
It looks like you're using the request module, but didn't tag it as such.
If I'm right, then your options object is incorrect, from the documentation there's not a data key that's respected. Instead, you should use body or formData or json depending on what kind of data you're pushing up. From your headers, I'd go with json.
var requests = [{
url:url,
method: 'POST',
headers: { // Content-Type header automatically set if json is true
'Authorization': 'Bearer ' + req.cookies.apitoken
},
json: finalArr,
}];

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