We are trying to access a HTTPS REST API(GET) using nodeJS with request module, but it is throwing 401 - unauthorized.
We tried various options - provided like oauth_token OR user id & password, everything returns the same 401 status. I have given below the code snippet any suggestions would be helpful.
Note: We are running behind a proxy and we have set http proxy env variables, not sure if this will have anything to do with 401 (I don't think so but I am not 100 percent sure)
var request = require('request');
var options = {
uri: 'https://www.yammer.com/api/v1/messages.json',
auth: {
user: 'test',
pass: 'test-1',
sendImmediately: false
}
}
request(options, function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log("Response is " + response);
} else {
console.log("Error is" + error);
console.log("Body is" + body);
console.log("Full response is" + JSON.stringify(response, null, 2));
}
});
Thanks.
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)
}
});
I'm trying to build a CLI that uses the GitHub api. I instantly run into a road block. Although I've read the introductory docs up and down, I don't see what is wrong in the following code.
var userData = require('../userData');
var request = require('request');
module.exports = {
hitEndpoint: function() {
var username = "<redacted_user_name>",
password = "<redacted_password>",
auth = "Basic " + new Buffer(username + ":" + password).toString("base64");
var options = {
method: 'get',
url: " https://api.github.com/<redacted_user_name>",
headers: {
"Authorization": auth,
"User-Agent": "<redacted_whatever_doesnt_matter>"
}
}
request(options, function (error, response, body) {
console.log('error:', error); // Print the error if one occurred
console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received
console.log('body:', body); // Print the HTML for the Google homepage.
});
},
}
prints:
error: null
statusCode: 404
body: {"message":"Not Found","documentation_url":"https://developer.github.com/v3"}
To get your own profile you'll want to hit the authenticated user endpoint, you shouldn't replace this with your own username, GitHub will know who you are based on your authentication string:
https://api.github.com/user
To get another user's profile you'll want to hit the users endpoint:
https://api.github.com/users/:username
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);
We are trying to get node to use a ssl based api on another machine and it's failing with a socket hang up error. I'm putting the code below. Basically, on one machine we have a asp.net web api based api set up to accept a request, and on another we have a tomcat spring mvc based api accepting requests. Both apis work with fiddler, postman, other sites sending identical requests, however with node sending to the tomcat site, we get an immediate socket hangup error. We're really struggling trying to figure out what is wrong. So it will work correctly with one ssl based url, but fail with the other, and we've confirmed both sites work. The code is below. Is there something we're missing?
app.post('/site/app/getvalue', function(req, res){
process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";
console.log("Request: ");
console.log(req.body);
var options = {
method: 'post',
body: req.body,
json: true,
//url: 'https://X.X.X.X/getvalue/',
url : 'https://X.X.X.X:8443/getvalue/',
rejectUnauthorized: false,
headers: { 'Content-Type' : 'application/json'}
};
request(options,
function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log("Response: ");
console.log(body);
console.log("Transaction Count: " + body.TransactionCount);
res.send(body);
}
else {
console.log("ERROR: " + error);
res.send(500);
}
}
);
});
We get: ERROR: Error: socket hang up
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.