NodeJs/Electron, Request Post not catching Request Body - node.js

I've got some simple code that isn't working. Have tried several libraries, all of which wind up giving me similar errors. I'm convinced the website itself is somehow rejecting the request. It's wrapped in an electron application.
This is the response I receive (not a typical error - the error is in the response body)
{"error":{"code":2,"message":"Query missing. `Are ya gonna search for something or what?`"}}
This is a snippet of relevant code, present in the main.js of my app:
const request = require('request');
.
.
.
ipcMain.on('request-mainprocess-action', (e, args) => {
request({ body: JSON.stringify({"query": {"status": {"option": "online"}, "stats": [{"type": "and", "filters": []}]},"sort": {"price": "asc"}}}),
followAllRedirects: true,
headers: {
'Content-Type': 'application/json',
'Referer': 'www.pathofexile.com/trade/search/Incursion',
'X-Requested-With': 'XMLHttpRequest' },
method: 'POST',
url: 'http://pathofexile.com/api/trade/search/Incursion'}, callback);
function callback(error, response, body) {
if (!error && response.statusCode == 200) {
e.sender.send('mainprocess-response', {
type: args.query,
data: body
});
} else {
console.log(body);
}
}
});
I've tried a few variations of this, like calling request.post or using a json object and the flag json:true. I've also tried some other libraries, like http, https, and axios(axiom?).... No luck.
I was able to make it work with little effort using an IntelliJ http post script/snippet:
POST https://www.pathofexile.com/api/trade/search/Incursion
Referer: https://www.pathofexile.com/trade/search/Incursion
Content-Type: application/json,
X-Requested-With: XMLHttpRequest
{"query": {"status": {"option": "online"}, "stats": [{"type": "and", "filters": []}]},"sort": {"price": "asc"}}
The above returns a rather large bit of text,
Response code: 200 (OK); Time: 1426ms; Content length: 6755 bytes
Unfortunately I cannot call this from Electron :)... Could really use your help.
Thanks,

Just add this line to your request-headers:
'Host': 'www.pathofexile.com',
And here is the complete code which I run it from my side with node command:
const request = require('request');
var payload = JSON.stringify({"query": {"status": {"option": "online"}, "stats": [{"type": "and", "filters": []}]},"sort": {"price": "asc"}});
request({
body: payload,
followAllRedirects: true,
headers: {
'Content-Type': 'application/json',
'Referer': 'www.pathofexile.com/trade/search/Incursion',
'Host': 'www.pathofexile.com',
'X-Requested-With': 'XMLHttpRequest' },
method: 'POST',
url: 'http://pathofexile.com/api/trade/search/Incursion'}, callback);
function callback(error, response, body) {
if (!error && response.statusCode == 200) {
console.log('Success: \n'+body);
} else {
console.log("Error: \n"+body);
}
};
And I got this result as shown on this screenshot:

Related

Can't get basic authentication in node.js/request module to work with PUT or POST request

I am trying to call a REST API endpoint from node.js, using the 'request'module. I keep getting a 401 invalid credentials response. Code is as follows:
var q = {
'boothNumber':'1400',
'databaseName':'demo',
'exhibitorId':'T19',
'comment':'N/A'
};
var options = {
url: 'https://api2.e-----d.com',
path: '/edgewebapi/ACTDev2/booths/hold',
method: 'PUT',
//headers: headers,
headers: { 'Authorization':'Basic VUdFUTdDZkY6RmJsb0QyWiQ='},
body: JSON.stringify(q)
}
request(options, function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log('Request successful.');
}
else {
console.log('Error = ' + error) ;
}
})
I have read every post on this site to try to solve it, tried every suggestion, including the 'auth' option below (in a headers object):
I tried using a headers object (below):
var headers = {
'Accept': 'application/json',
'Authorization': 'Basic VUdFUTdDZkY6RmJsb0QyWiQ='
/*
'auth': {
'user': 'UGEQ7CfF',
'pass': 'FbloD2Z$',
'sendImmediately': false
}
*/
}
I retried using axios, code below, and everything works. (I really need to keep using the request module though, because I am using this in AWS Lambda and the axios causes me other issues...):
axios.put(
'https://api2.e---d.com/edgewebapi/ACTDev2/booths/hold?boothNumber=1400&databaseName=demo&exhibitorId=T19',
{},
{ headers : {'Authorization': 'Basic VUdFUTdDZkY6RmJsb0QyWiQ=' } }
).then(function(response) {
console.log(response.status);
}).catch(function(error) {
console.log(error);
});
Can anyone help by providing the correct code to do this? I have spent days trying to figure it out. Thanks.

NodeJS + Request REST API

I have the following code an i try to connect to a server and get a json response from the server but somthing is wrong becouse i get this error: error null 401. Can you please help me to identify the error on this code or to find what is missing. Thank you!
var request = require('request');
var apiurl = "externalserverurl:6080";
var options = {
"regid" : "username",
"password" : "password",
"uri" : apiurl,
"registrar_domain" : "mydomain.com",
"lang" : "en",
json: true,
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'User-Agent': 'request'
}
};
function callback(error, response, body) {
if (!error && response.statusCode == 200) {
console.log('body:', body);
} else {
console.log('error', error, response && response.statusCode);
}
}
request(options, callback);
As #kay already mentioned, errorcode 401 means that your request is unauthorized. Given that there are a lot of different possible authentication methods (basic auth, digest auth, OAuth, you name it), you should refer to your target server and clarify which auth method you should use before trying to actually modify your code.
You could also check the response body, it could contain some hints about what exactly the server expects but doesn't receive.

Node.js request module

I'm trying to use the request module to send post request to another service but the callback never fires. Here is what I'm doing right now:
request.post(
`http://localhost:3002/users/login`,
{
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({userDetails})
},
function (error, response, body) {
if (!error && response.statusCode == 200) {
const data = JSON.parse(body);
console.log(data);
} else {
console.log('Request has failed. Please make sure you are logged in');
res.status(401).send(body);
}
}
);
The callback function never fires. On the other hand, if I try to send this exact request with Postman, the server gets the request. What am I doing wrong?
Syntax error maybe? Try with:
request({
method: 'POST',
url: 'http://localhost:3002/users/login',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({userDetails})
},
function (error, response, body) {
// Now it should fire the callback.
console.log('okay');
});
Works like a charm on my side.
Edit: If it still doesn't work, my bet is that the cross-origin resource sharing is not enabled for the localhost:3002 server you're trying to access. Here's the easiest way to enable it.

Unable to overwrite header attribute Content-type in http calls

Following is the code which sends the request -
var requestData = {
"trigger_id":global.config.primusConfig.trigger_id,
//"mobile":global.config.primusConfig.trigger_id,
"email": global.config.primusConfig.email,
"params":{
"Amount":"200"
}
/*,
"files":{
“sample.pdf” : fileData
}*/
};
request({
headers: {
'cid': global.config.primusConfig.client_id,
'datetime': datetime,
'hash': hash,
'Content-type': 'application/json',
'From':'sandeepan#example.com'
},
url: global.config.primusConfig.apiEndPoint,
method: 'POST',
form: requestData,
body : req.rawBody,
},
function(error,httpResponse,body) {
console.log("Response handling part "+global.config.primusConfig.apiEndPoint+" formdata "+JSON.stringify(requestData));
if(error) {
console.log("Error "+error);
}
else {
console.log("Not error case- Body: "+body+" httpResponse:"+JSON.stringify(httpResponse));
callback();
}
});
From the logged httpResponse, I can see the request which was actually sent -
httpResponse:{"statusCode":500,"body":"\n <h1> 500 - Internal server error </h
1>\n <h2> </h2>\n","headers":{"content-type":"text/html; charset=utf-8","date"
:"Tue, 31 Oct 2017 15:19:13 GMT","etag":"W/\"38-3b8a0f21\"","x-powered-by":"Expr
ess","content-length":"56","connection":"Close"},"request":{"uri":{"protocol":"h
ttps:","slashes":true,"auth":null,"host":"domain.com","port":4
43,"hostname":"domain.com","hash":null,"search":null,"query":n
ull,"pathname":"/sendnotification","path":"/sendnotification","href":"domain.com/sendnotification"},"method":"POST","headers":{"cid":"
19","datetime":"2017-10-31 00:00:00","hash":"88072482e5125ed69f28ce60af859653049
9e11d","Content-type":"application/x-www-form-urlencoded","From":"sandeepan#exam
ple.com","content-length":70}}}
I can see the From attribute set to sandeepan#example.com, as I modified it, but I cannot see the Content-type changed to application/json.
Can someone explain? Any pointers?
form option implies application/x-www-form-urlencoded content-type: https://github.com/request/request/blob/master/request.js#L1249
If you are sending json, you need to use json option instead: https://github.com/request/request/blob/master/request.js#L1278
There is no need to set content-type explicitly:
request({
headers: {
'cid': global.config.primusConfig.client_id,
'datetime': datetime,
'hash': hash,
'From':'sandeepan#example.com'
},
url: global.config.primusConfig.apiEndPoint,
method: 'POST',
json: requestData
},

Github Web API authorization issue - returns "Not found"

Since I don't find anyone with the same problem, I'm hoping it's a simple thing. And I'm fairly newb.
It's a Node/Express app and I'm trying to connect to Githubs Web API and retrieve issues for a certain repo. I have generated a personal token and I'm using it with Basic Authorization. When I try to connect I get: "Not found". Github state that where authentication is necessary they return 404/403, and I get 404, so it has to be something with the authentication. The repo has issues.
There shouldn't be a problem with the token, I choosed "repo" as access scope.
Actually I have no idea what I'm doing making HTTP requests but I've tried with both request and http. So among other things I'm wondering if it's something with the Authorization header that's wrong.
I paste the code I have right now using request, and the body returned. Any help is greatly appreciated.
const githubToken = process.env.TOKEN;
let options = {
url: "https://api.github.com/repos/myOrg/myRepo/issues/",
headers: {
"Authorization": "Basic " + githubToken,
"User-Agent": "Mozilla/5.0",
"Content-Type": "application/json"
}
};
let requestCB = function(error, response, body) {
if (error) {
console.log(error);
} else if (!error && response.statusCode == 200) {
let info = JSON.parse(body);
console.log("Success");
console.log(info);
} else {
console.log(response);
console.log(body);
}
};
request(options, requestCB);
And the end of the response and the body:
read: [Function],
body: '{"message":"Not Found","documentation_url":"https://developer.github.com/v3"}' }
{"message":"Not Found","documentation_url":"https://developer.github.com/v3"}
EDIT:
So I found help with this, posting solution below. I guess the problem was that the accept-header have to be included. Perhaps the hostname, path and uri have to be in this format aswell.
let options = {
headers: {
"User-Agent": "GitHub-username",
"Accept": "application/vnd.github.v3+json",
"Authorization": "token " + githubToken
},
hostname: "api.github.com",
path: "/repos/org/repo/issues",
uri: "https://api.github.com/repos/org/repo/issues",
method: "GET"
};
Basic authentication require no token
Basic Authentication
curl -u "username" https://api.github.com
So in your request, you can omit githubToken
See the docs for more information about types of authentication
Using a token
var request = require('request');
var options = {
url: 'https://api.github.com/?access_token=OAUTH-TOKEN',
headers: {
"Authorization": "token ",
"User-Agent": "Mozilla/5.0",
"Content-Type": "application/json"
}
};
function callback(error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body);
}
}
request(options, callback);

Resources