Sending an API request with Nodejs - node.js

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

Related

Pass post data to another url and get url response in post response

I am trying to pass some data to /card then filter it and send to a url and the final response of my /card need to be response send from the url.
app.post('/card', (req, res) => {
var testData = req.body.orderId;
if(testData!=null){
var options = {
uri: 'https://localhost',
headers: {'content-type' : 'application/json'},
method: 'POST',
json: {"longUrl": testData}
};
request(options, function (error, response, body) {
if (!error && response.statusCode == 200) {
// res.json(testData);
console.log(body.id) // Print the shortened url.
}
});
}
});
You can use Node.js core module http to make an http request from within your Node application.
You can consult the official documentation and various options here https://nodejs.org/api/http.html#http_http_request_options_callback

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.

retrieve JSON response of a POST request in nodeJS

I am sending s POST request to a service and it is supposed to return a JSON in response. I see the POST is successful but I dont get anything in response back. What am I missing? Below code
var headers = {
"Accept":"application/json",
"Content-Type":"application/json",
"Authorization": ("Basic " + new Buffer("admin:password").toString('base64'))
}
// Configure the request
var options = {
url: 'myservice-url',
method : 'POST',
headers : headers
}
// Start the request
request(options, function (error, response, body) {
if (!error && response.statusCode == 200) {
// Print out the response body
var str = JSON.stringify(body, null, 2);
console.log(str)
}
})
First of all, need to confirm if you have properly installed the following:
https://github.com/request/request
Then require it in your file like this:
var request = require('request');
request.post({
url: "",//your url
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
rejectUnauthorized: false,//add when working with https sites
requestCert: false,//add when working with https sites
agent: false,//add when working with https sites
form: {
whateverfieldnameyouwant: "whatevervalueyouwant"
}
},function (response, err, body){
console.log('Body:',JSON.parse(body));
}.bind(this));

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

invalid oauth2 token request

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.

Resources