curl succeeds with oath2 but fails with node.js request - node.js

The following curl request works properly, returning the authentication token as it should
curl POST -s -d "grant_type=password&username=someusername&password=somepassword&client_id=someid&client_secret=somesecret&response_type=token" "someurl"
when the equivalent request in node.js fails
let url = someurl
var dataString = 'grant_type=password&username=somename&password=somepassword&client_id=someid&client_secret=somesecret&response_type=token';
var options = {
url: url,
method: 'POST',
body: dataString,
allow_redirects : true
};
function callback(error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body);
}
console.log(error)
console.log(body)
}
request(options, callback);
The error is
{"error":"unauthorized","error_description":"An Authentication object was not found in the SecurityContext"}
Which may only be specific to this code. At any rate, what differences (in default parameters presumably or configuration) could explain this difference. Note, the programs fails both with and without allow_redirects option, but redirection should be allowed.
This is node v7.10.0 running on macosx and request 2.81.0

My first assumption would be that you're missing the headers required for your request
let url = someurl
var dataString = 'grant_type=password&username=somename&password=somepassword&client_id=someid&client_secret=somesecret&response_type=token';
var options = {
url: url,
method: 'POST',
body: dataString,
headers: { 'content-type': 'application/x-www-form-urlencoded' },
allow_redirects: true
};
function callback(error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body);
}
console.log(error)
console.log(body)
}
request(options, callback);
If this isn't correct, let me know and i'll resolve the answer

Related

HTTP POST with node.js and request library isn't outputting anything

I'm just testing to see if my POST request to a website works, but it isn't outputting anything. When I use RunKit, it shows an output, but not in my powershell. Am I doing something wrong or is there no output? How can I make it show the output? Here is my code:
var request = require('request');
request.post(
'My_API_URL',
{ json: { "text":"this is my text" } },
function (error, response, body) {
console.log(body);
}
);
What i suggest you, is to update your code like this and try again:
var request = require('request');
var options = {
uri: 'My_API_URL',
method: 'POST',
json: {
"text":"this is my text"
}
};
request(options, function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body);
}
});
Let me know if the result is the same.
Check this link. You should do post requests like this:
var request = require('request');
var body = JSON.stringify({
client_id: '0123456789abcdef',
client_secret: 'secret',
code: 'abcdef'
});
request.post({
url: 'https://postman-echo.com/post',
body: body,
headers: {
'Content-Type': 'application/json'
}},
function (error, response, body) {
console.log(body);
}
);

Communication between servers using Express and Request

Following scenario:
I got two servers, one server a Website, the other manages a database. The Website sends requests to its server, the request is passed to the backend server and a data set from the database should be returned.
I am using Express on both servers, the one serving the website also has the Request package.
Code on first server:
request.post({
headers: {'content-type' : 'application/x-www-form-urlencoded'},
url: 'http://localhost:8081/getDataset',
body: "data="+data
},
function(error, response, body){
if (!error && response.statusCode == 200) {
console.log(body)
res.send(body)
}
}
)
Code on second server:
getFromEigenschaft (req, res) {
var data = req.body.data
console.log(req.body) //logs {}
//do database stuff with data
return res.status(200).send(dataSet)
}
On the second server req.body is an empty object though. What am I doing wrong?
Found the answer:
The body object can be set to a JSON, just as I want to, but the JSON option must be set to true:
request.post({
headers: {'content-type' : 'application/x-www-form-urlencoded'},
url: 'http://localhost:8081/getDataset',
json: true,
body: data
},
function(error, response, body){
if (!error && response.statusCode == 200) {
console.log(body)
res.send(body)
}
}
)

How to download GitHub release asset from private repo using node

I would like to use node.js request module to download a release asset from a private repo. It works fine with the following cURL command:
curl -O -J -L \
-H "Accept: application/octet-stream" \
https://__TOKEN__:#api.github.com/repos/__USER__/__REPO__/releases/assets/__ASSET_ID__
but it fails when I try using the request module:
var request = require('request');
var headers = {
'Accept': 'application/octet-stream'
};
var API_URL = "https://__TOKEN__:#api.github.com/repos/__USER__/__REPO__"
var ASSET_ID = __ASSET_ID__
var options = {
url: `${API_URL}/releases/assets/${ASSET_ID}`,
headers: headers,
};
function callback(error, response, body) {
if (error) {
console.error(error);
}
console.log(response.statusCode)
if (!error && response.statusCode == 200) {
console.log(body);
}
console.log(options.url);
}
var req = request(options, callback);
console.log(req.headers)
I have double checked that the resulting URL when using node is the same as the one I use with cURL.
I receive a 403 statusCode in the response. I do not understand why.
UPDATE:
While looking at the headers that are actually sent, I have found that the it uses
{ Accept: 'application/octet-stream',
host: 'api.github.com',
authorization: 'Basic __DIFFERENT_TOKEN__' }
I do not understand why the token is changed.
some references: https://gist.github.com/maxim/6e15aa45ba010ab030c4
GitHub API requires a user agent (https://github.com/request/request#custom-http-headers)
It is also important to set the encoding to null in order to have a buffer and not a string in the body (Getting binary content in Node.js using request)
The working version of the code is thus:
var request = require('request');
var headers = {
'Accept': 'application/octet-stream',
'User-Agent': 'request module',
};
var API_URL = "https://__TOKEN__:#api.github.com/repos/__USER__/__REPO__"
var ASSET_ID = __ASSET_ID__
var options = {
url: `${API_URL}/releases/assets/${ASSET_ID}`,
headers: headers,
encoding: null // we want a buffer and not a string
};
function callback(error, response, body) {
if (error) {
console.error(error);
}
console.log(response.statusCode)
if (!error && response.statusCode == 200) {
console.log(body);
}
console.log(options.url);
}
var req = request(options, callback);
console.log(req.headers)
Thanks to Marko Grešak.

Node 'request' method doesn't execute

I have my code trying to execute my request method, but it's not going in there. I'm setting up my objects correctly, but what I log doesn't get executed. Am I setting it up incorrectly?
req = require("request");
var headers = {
"Content-Type": "json/application",
"Authorization": "M6V9Jt2HJa8bcYCjd1xItrVaw1dcHDEY5FRpxdfojhI"
}
var options = {
url: "'http://api.nytimes.com/svc/topstories/v1/home.json?api-key="+NYTIMESKEY,
method: 'GET',
headers: headers
}
for(var i = 0; i < parsed.results.length; i++){
abstracts.push(parsed.results[i].abstract);
var url = formatUrl(abst, "https://api.datamarket.azure.com/data.ashx/amla/text-analytics/v1/GetSentiment?Text=");
var sentStr = '';
console.log("in there");
req(options, function(error, response, body){
if (!error && response.statusCode == 200){
console.log(body);
console.log("executing thing");
}
});
}
First of all, you have a misprint in your options object.
var options = {
url: "'http://api.nytimes.com/svc/topstories/v1/home.json?api key="+NYTIMESKEY,
"url" param has extra single quote. When you try to call req function with current url, you'll get "Type error" (invalid protocol).
Secondly, the reason your function doesn't call, could be empty parsed.results array. I've simplified a bit your code. And now req function is called.
req = require("request");
var headers = {
"Content-Type": "json/application",
"Authorization": "M6V9Jt2HJa8bcYCjd1xItrVaw1dcHDEY5FRpxdfojhI"
}
var options = {
url: "http://api.nytimes.com/svc/topstories/v1/home.json?api-key=" + "something_you_nedd",
method: 'GET',
headers: headers
}
var sentStr = '';
console.log("in there");
req(options, function(error, response, body){
console.log("on answer");
if (!error && response.statusCode == 200){
console.log(body);
console.log("executing thing");
}
});

How to POST a new issue comment to github api?

I can't seem to figure out how to do this. I have a repo where I test things and everything should be pretty straight forward, but.
I am using node.js, but that is not much relevant in this problem:
var request = require('request');
var options = {
uri: 'https://api.github.com/repos/capaj/gitup/issues/1/comments',
method: 'POST',
headers: {'User-Agent': 'bot'},
json: {
"body": 'my uber comment'
}
};
request(options, function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body);
} else {
//I always get 404
}
});

Resources