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");
}
});
Related
I am setting up an API connection via Node.js. I had some predefined cURL code which I converted into Node.js code, which I have provided below. Until now everything works fine, I am displaying the value I need (token) inside the console window.
However, I am wondering how I can use this token variable in another function? So I somehow have to save it as a global variable, but until now that didn't work.
var request = require('request');
var headers = {
'content-type': 'application/x-www-form-urlencoded',
'Authorization': 'XXXXXXXXXXXXXXXXX'
};
var dataString = 'grant_type=client_credentials';
var options = {
url: 'XXXXXXXXXXXXXXXX',
method: 'POST',
headers: headers,
body: dataString
};
function callback(error, response, body) {
if (!error && response.statusCode == 200) {
var str = body;
token = str.split('\"')[3];
console.log(token);
}
}
request(options, callback);
You can access token only when request() complete and calls the callback function. This is due to the non-blocking nature of node.js - when you start a request the code doesn't block and you can access its response only when it completes and call the callback function. Hence you first define the callback function and pass it to request as an argument. If you want to access token you can create another function and call it inside the callback.
var request = require('request');
var headers = ...
var dataString = ...
var options = ...
function doStuffWithToken(token) {
console.log(token)
}
function callback(error, response, body) {
if (!error && response.statusCode == 200) {
var str = body;
token = str.split('\"')[3];
doStuffWithToken(token);
}
}
request(options, callback);
You can also use promises for better code:
var request = require('request');
function getToken() {
var headers = ...
var dataString = ...
var options = ...
return new Promise((resolve, reject) => {
request(options, (error, response, body) => {
if (error) return reject(error)
if (response.statusCode == 200) {
var str = body;
token = str.split('\"')[3];
resolve(token);
}
}
}
}
getToken()
.then((token) => {
// here you can access the token
console.log(token)
})
.catch((error) => {
console.error('unable to retrieve token', error)
})
Here we create a wrapper around our request. getToken() returns a promise object that you can use to register two handlers for when it resolves successfully and for when it rejects and throw an error.
You can use getToken() also with the await/async keyword
var request = require('request');
function getToken() {
var headers = ...
var dataString = ...
var options = ...
return new Promise((resolve, reject) => {
request(options, (error, response, body) => {
if (error) return reject(error)
if (response.statusCode == 200) {
var str = body;
token = str.split('\"')[3];
resolve(token);
}
}
}
}
async function main() {
let token = await getToken()
console.log(token)
}
main()
.then(...)
.catch(...)
Further readings:
Don't block the event loop
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);
}
);
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
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.
I've wrote a nodejs app for betfair but my session id is expiring and I can't figure out how to write the keep alive code. Here is documentation for it: https://api.developer.betfair.com/services/webapps/docs/display/1smk3cen4v3lu3yomq5qye0ni/Keep+Alive
I've found a solution. I converted the curl command on this site: http://curl.trillworks.com/#node.
This is my code:
var request = require('request');
var appkey = xxxx;
var ssid = xxxx;
function keepAlive() {
var options = {
url: 'https://identitysso.betfair.com/api/keepAlive',
headers: {
'Accept': 'application/json',
'X-Application': appkey,
'X-Authentication': ssid
}
};
function callback(error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body);
}
}
request(options, callback);
}