Request API node js using bearer token - node.js

I tried doing the following:
request({
url: 'https://vdms-dev.clientsolve.com/evoDMDev/api_event.php',
headers: {
'Authorization': 'Bearer 71D50F9987529'
}
}, function(err, res) {
console.log(res);
});
The log is showing undefined but when I try it on Postman it seems to be working fine.
Any help would be appreciated!

Since your are calling https host (https://evodms-dev.clientsolve.com/evoDMSDev/api/api_event_all.php), request client will throws an error while doing SSL handshake,
thats why you got response as undefined. Inorder to check the exact error response log the error console.error("Error Response : ", err)
Checkout this working snippet with error handling.err
Note: Now you will get Invalid Bearer Token error, Enter valid Bearer token
const request = require('request');
request({
url: 'https://evodms-dev.clientsolve.com/evoDMSDev/api/api_event_all.php',
headers: {
'Authorization': 'Bearer 71D50F9987529'
},
rejectUnauthorized: false
}, function(err, res) {
if(err) {
console.error(err);
} else {
console.log(res.body);
}
});

Related

Cannot send authorization bearer token throught axios

When I check in postman and sent the request to an api endpoint with the token works good:
But when I make the same request in expressjs to the api it sent me an unauthorized response:
Request:
try {
const response1 = await axios.get(`https://url/payment/pse/banks`,{headers: {
'Content-Type': 'application/json',
'Authorization':`Bearer ${token}`
}})
console.log("lista",response1.data);
} catch (error) {
console.log(error.response.data)
}
Response:
{
success: false,
titleResponse: 'Unauthorized.',
textResponse: 'Unauthorized.',
lastAction: '',
data: { token: '' }
}
What am I doing wrong?

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

Axios Proxy Configuration causing Bad Request

I am trying to send a request to the particle cloud from a NodeJS application.
I am using Axios to make the PUT request. The application sends the request through a proxy server which is configured as well.
// axios proxy - not working
axios.default.put("https://api.particle.io/v1/devices/<deviceId>/ping", {}, {
proxy: {host: <proxy_ip>, protocol:'http', port:<port_no>},
headers: {
authorization: "Bearer <access_token>"
}
}).then((response) => {
console.log("Success", response.data);
}).catch((error) => {
console.log("Failed", error);
});
Error Message: Request failed with status code 400
When I send this request I get a 400 Bad Request response from the particle cloud.
But when I send the same request using the request module of NodeJS, the request is successful.
var options = {
method: 'PUT',
url: 'https://api.particle.io/v1/devices/<device_id>/ping',
proxy: {hostname: <proxy_ip>, protocol:'http', port:<port_no>},
headers:
{
authorization: 'Bearer <access_token>'
},
form: false
};
request(options, function (error, response, body) {
if (error) throw new Error(error);
console.log(response);
});
Response: body: '{"online":false,"ok":true}'
The request also works when the application was deployed on the open network and axios was used without the proxy configuration.
// axios without proxy - working
axios.default.put("https://api.particle.io/v1/devices/<deviceId>/ping", {}, {
headers: {
authorization: "Bearer <access_token>"
}
}).then((response) => {
console.log("Success", response.data);
}).catch((error) => {
console.log("Failed", error);
});
Questions:
Why is the request from Axios failing with proxy configuration?
Is this an inherent issue with Axios?
Regards.
Axios itself has a bug which isnt fixed yet.
To overcome this issue, https-proxy-agent can be used instead of axios proxy.
const HttpsProxyAgent = require('https-proxy-agent')
axios.default.put("https://api.particle.io/v1/devices/<deviceId>/ping", {}, {
headers: {
authorization: "Bearer <access_token>"
},
proxy: false,
httpsAgent: new HttpsProxyAgent('http://proxy_domain:port')
}).then((response) => {
console.log("Success", response.data);
}).catch((error) => {
console.log("Failed", error);
});

nodejs request post large json fail

I am trying to post large json to a http server(a grafana server actually):
here is my code:
const http = require('http')
const request = require('request')
const fs = require('fs')
const opts = {
hostname: 'myip',
port: 3000,
path: '/api/dashboards/uid/KPEiIQVWk',
method: 'GET',
timeout: 5000,
headers : {
'Authorization' : 'Bearer ********************************************',
'Accept' : 'application/json',
'Content-Type' : 'application/json'
}
}
const req = http.request(opts, res => {
console.log(`Fetch: statusCode: ${res.statusCode}`)
var origin = ''
res.on('data', d => {
origin += d
})
res.on('end', function(){
dash = JSON.parse(origin)
dash.dashboard.panels.forEach(p => {
if(p.id == 26){
fs.readFile(__dirname + '/grafana/pm/branch-graph.html','utf-8', function(err, newPanel){
if(err){
console.log(err)
}
p.content = newPanel
const fresh = JSON.stringify(dash)
const updateOptions = {
uri: 'http://myip:3000/api/dashboards/db',
method: 'post',
headers : {
'Authorization' : 'Bearer *************************',
'Accept' : 'application/json',
'Content-Type' : 'application/json',
'Content-length' : fresh.length
},
json: fresh
}
fs.writeFile('tmp.json', fresh, function(err){
if(err){
console.error(err)
}
})
request(updateOptions, function(error, response, body){
console.log(`update: statusCode=${response.statusCode}`)
console.log(`update: ${body}`)
})
})
}
})
})
})
req.on('error', error => {
console.error(error)
})
req.on('timeout', () => {
req.abort()
})
req.end()
as you can see, I first fetch a grafana dashboard's source, then make some udpate, then post it back to grafana server. but always get 400 error. The strange thing is that if I dump the json to a file and use curl to post, it will work.
curl -vH "Authorization: Bearer $TOKEN" -H "Expect:" -d #tmp.json -H "Content-Type:application/json" http://myip:3000/api/dashboards/db
the whole json is about 40000+ bytes. any hint on this? I am not very famillar with nodejs. I am just trying to write some CI scripts.
First, I don't think it's necessary to use both the http and request modules. http is a module built into nodejs, and request is an npm package.
I recommend you use the npm request package because it's easier. You can read its documentation here: https://www.npmjs.com/package/request#http-authentication
Second, the options you're passing to the request module is not formatted correctly, I think this is why it is not working. With your current code, I would console.log('POST error', error); to print out the error. The correct options for the request module is proposed below.
const options = {
url: 'https://myip:3000/api/dashboards/db',
body: fresh, // the json from the fs.read callback
auth: {
'bearer': 'bearerToken'
},
json: true // from docs: If json is true, then body must be a JSON-serializable object.
}
request.post(
options,
(err, httpResponse, body) => {
console.log(err, body);
});

Axios login request: Unauthorized, request status code 401

I'm trying to get an authorization token by making a request to an api using axios:
axios({
method: 'post',
url: 'http://62.110.134.187/api/signin',
headers: { 'content-type': 'application/x-www-form-urlencoded' },
auth: {
username: usr,
password: pwd
}
}).then(function (response) {
console.log(response)
}).catch(function (error) {
console.log('Error: ' + error)
})
I'm getting always status code 401(Unauthorized):
Error: Request failed with status code 401
Where I'm doing wrong?
The fact is that making the same request using python works fine:
payload = "username=%s&password=%s" % (usr,pwd)
headers = {'content-type': 'application/x-www-form-urlencoded'}
response = requests.request("POST", url_login, data=payload, headers=headers)
print(response.text)
data = response.json()
token = data["token"]
By sending username and password in auth: {} in axios, you are doing the basic-authentication, basically sending Authorization: basic <base64(user:pass)> header.
As per working python program, you need to send the username and password as part of the request body. You need to serialize the body params for url-encoded content type as well.
e.g.
const querystring = require('querystring');
axios({
method: 'post',
url: 'http://62.110.134.187/api/signin',
headers: { 'content-type': 'application/x-www-form-urlencoded' },
data: querystring.stringify({
username: usr,
password: pwd
})
}).then(function (response) {
console.log(response)
}).catch(function (error) {
console.log('Error: ' + error)
})

Resources