I'm developing a node application which needs to authenticate with google. When I request a token, https://accounts.google.com/o/oauth2/token responds with:
error: 400
{
"error" : "invalid_request"
}
I've tried making the same request in curl, and have received the same error, so I suspect there is something wrong with my request but I can't figure out what. I've pasted my code below:
var request = require('request');
var token_request='code='+req['query']['code']+
'&client_id={client id}'+
'&client_secret={client secret}'+
'&redirect_uri=http%3A%2F%2Fmassiveboom.com:3000'+
'&grant_type=authorization_code';
request(
{ method: 'POST',
uri:'https://accounts.google.com/o/oauth2/token',
body: token_request
},
function (error, response, body) {
if(response.statusCode == 201){
console.log('document fetched');
console.log(body);
} else {
console.log('error: '+ response.statusCode);
console.log(body);
}
});
I've triple checked to make sure all the data I'm submitting is correct and i'm still getting the same error. What can I do to debug this further?
It turns out that request.js (https://github.com/mikeal/request) doesn't automatically include the content-length to the headers. I added it manually and it worked on the first try. I've pasted the code below:
exports.get_token = function(req,success,fail){
var token;
var request = require('request');
var credentials = require('../config/credentials');
var google_credentials=credentials.fetch('google');
var token_request='code='+req['query']['code']+
'&client_id='+google_credentials['client_id']+
'&client_secret='+google_credentials['client_secret']+
'&redirect_uri=http%3A%2F%2Fmyurl.com:3000%2Fauth'+
'&grant_type=authorization_code';
var request_length = token_request.length;
console.log("requesting: "+token_request);
request(
{ method: 'POST',
headers: {'Content-length': request_length, 'Content-type':'application/x-www-form-urlencoded'},
uri:'https://accounts.google.com/o/oauth2/token',
body: token_request
},
function (error, response, body) {
if(response.statusCode == 200){
console.log('document fetched');
token=body['access_token'];
store_token(body);
if(success){
success(token);
}
}
else {
console.log('error: '+ response.statusCode);
console.log(body)
if(fail){
fail();
}
}
}
);
}
from here How to make an HTTP POST request in node.js? you could use querystring.stringify to escape query string of request parameters. Plus you'd better add 'Content-Type': 'application/x-www-form-urlencoded' for POST request.
post here the final string generated from token_request var.that may have something wrong. or may be authentication code is expired or not added correctly to the URL. Usually code has '/' in it that needs to escaped.
Related
I have a problem with getting the xml from a get-request from this URL: https://feeds.meteoalarm.org/feeds/meteoalarm-legacy-atom-austria
In the browser, it all works fine, and also when I check the content on https://reqbin.com/, I get as a response a nice xml.
When I run my code, I just get a 404 status code back:
const request = require('request');
var urlAtom = 'https://feeds.meteoalarm.org/feeds/meteoalarm-legacy-atom-austria'
request.post({
url: urlAtom,
timeout: 8000
}, function(error, response, body){
if (error){
adapter.log.error(error)
)
}
if (response.statusCode == 200){
adapter.log.info('Status Code:' + response.statusCode)
}
else{
adapter.log.warn('Status Code:' + response.statusCode)
}
});
I tried it with another URL, there I get a 200 status code, so it doesn't seem connected to my device. I am not sure if this server requests any special parameters or so (I already tried playing around with useragend). I would be happy about any idea.
It's a GET request, So change request.post to request.get,
const request = require('request');
const urlAtom = 'https://feeds.meteoalarm.org/feeds/meteoalarm-legacy-atom-austria'
const adapter = { log: console }
request.get({
url: urlAtom,
timeout: 8000
}, function (error, response, body) {
if (error) {
adapter.log.error(error)
}
if (response.statusCode == 200) {
adapter.log.info('Status Code:' + response.statusCode)
}
else {
adapter.log.warn('Status Code:' + response.statusCode)
}
});
var queryparam = "track:godsplan%20artist:drake&type=track&market=US&limit=10";
app.get('/get_track', function(req,res){
var options = {
url:"https://api.spotify.com/v1/search?"+queryparam,
headers: { 'Authorization': 'Bearer ' + access_token },
json: true
}
request.get(options, function(error, response, body) {
if(!error && response.statusCode === 200) {
console.log(body);
}
else{
console.log(error);
console.log(response.statusCode);
}
res.redirect('/#');
});
});
here is what I have and i am trying to get god's plan by drake to appear on my console when I run the server on local host and my access_token works but whenever i run the "/get_track" i get a bad request error, does anyone know why?
Your missing q=
var queryparam = "q=track:godsplan%20artist:drake&type=track&market=US&limit=10";
https://developer.spotify.com/documentation/web-api/reference/search/search/#request-parameters
what is that module "request" ?
(http, request-promise, request)
although I suppose that your request is simply not correctly formed
you need to try:
var queryparam = "q=track:godsplan%20artist:drake&type=track&market=US&limit=10";
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 set up a test end point here:
https://9wi46s5jzc.execute-api.us-east-1.amazonaws.com/test
For some baseline testing, I go to apitester.com and run two tests:
Firstly, a post request to: https://admin:password#9wi46s5jzc.execute-api.us-east-1.amazonaws.com/test (correct credentials) gives me output of:
{"isBase64Encoded":false,"statusCode":401,"headers":{"x-powered-by":"Express","content-type":"text/html; charset=utf-8","content-length":"0","etag":"W/\"0-2jmj7l5rSw0yVb/vlWAYkK/YBwk\""},"body":""}
Secondly, a post request to: https://admin:BADPASSWORD#9wi46s5jzc.execute-api.us-east-1.amazonaws.com/test (incorrect credentials) gives me output of:
{"message":"Unauthorized"}
So they're the baseline tests for what should happen.
When I run the following code:
const request = require('request');
const url = 'https://admin:password#9wi46s5jzc.execute-api.us-east-1.amazonaws.com/test';
request.post(url, function(err, res, body) {
console.log("body", body);
});
I get:
body {"message":"Unauthorized"}
Why is this happening?
According to the docs:
https://github.com/request/request
this is the way to do basic authentication.
So I'm expecting correct authorization but I'm not getting it. What am I doing wrong?
You should try it using this :
const proxyUrl = 'https://admin:password#9wi46s5jzc.execute-api.us-east-1.amazonaws.com/test';
const proxyRequest = request.defaults({ 'proxy': proxyUrl});
const options = {
url: '...',
headers: {
"Content-Type": "application/x-www-form-urlencoded",
"Authorization": "Bearer " + token // if this is how you handle auth and you already have the token
}
};
proxyRequest .get(options, function (error, response, body) {
if (error) {
next(error); // if you're using Express
}
console.log("body", body);
});
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);