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.
Related
I have implemented a GET request via request module in Nodejs in an application. I need to display the response over html page.
However, the response returned is undefined. Also, error and body message is also undefined.
I tried running it seperately with "node file.js", it works fine. Do I have to add anything else while using it in application.
I also tried htttp, curl-request and request-promise modules, all of them return undefined.
var request = require(['request']);
var headers = {
'Accept': 'text/json',
'X-Auth-Token': tk,
'User-Agent': 'request'
};
var options = {
url: 'https://api.github.com/repos/request/request',
headers: headers,
method: 'GET',
json: true
};
function callback(error, response, body){
console.log(response);
console.log(error);
if (!error && response.statusCode == 200) {
console.log(body);
return body;
}
}
request(options, callback);
I just had the same issue and found out that the server certificate was not fully trusted. As a TEMPORARY solution you could try to add strictSSL: false to your options object.
If it works like this (and assuming that you did not really send the request to "https://api.github.com/repos/request/request") contact the service provider and tell them about the certificate issues.
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.
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.
I've been trying to hit an API and get some data back from it (It's a free API not my own). So I've got my API token and I've had a look around and found that npm package request seems to be the best.
Within one of my routes I have,
request({
uri: "https://app.url-to-api:443/api/list-of-data",
method: "GET",
api_token: "my-api-token",
timeout: 10000,
followRedirect: true,
maxRedirects: 10
}, function(error, response, body) {
console.log(body);
});
So I'm getting "message":"Authorization has been denied for this request." back which is obviously because my API Token isn't getting passed through.
This might be a stupid question, but where do I actually put the API token to validate my request?
Thanks!
In request it would be something like this:
request.get('http://some.server.com/', {
'auth': {
'bearer': 'bearerToken'
}
});
More details on what you can do with request are in the docs.
You have to pass api tokens in request headers please see the documentation for request
var request = require('request');
var options = {
url: 'https://api.github.com/repos/request/request',
headers: {
'Access-Token': 'request'
}
};
function callback(error, response, body) {
if (!error && response.statusCode == 200) {
var info = JSON.parse(body);
console.log(info.stargazers_count + " Stars");
console.log(info.forks_count + " Forks");
}
}
request(options, callback);
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);
});