I am learning Node by developing an application that would hit the relevant server and extract its data.
Here, I am stuck as the relevant server demand to pass access token, and I'm not able to extract data successfully.
Here is my code
var options = {
method: 'GET',
url: 'any url',
auth : {
accessToken : "token here"
},
headers: {
'Accept': 'application/json'
}
}
But doing this i'm getting error Error: no auth mechanism defined
Access token seems to be perfect.
Sorry if this has been asked already but I cannot seem to find a straight answer.
Thanks for your efforts and time.
Try this :
var req = {
host: 'YOUR_URL',
method: 'GET',
headers: {
Authorization: your token
'Content-Type': 'application/json'
}
}
request(req, 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);
}
Related
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 the following code an i try to connect to a server and get a json response from the server but somthing is wrong becouse i get this error: error null 401. Can you please help me to identify the error on this code or to find what is missing. Thank you!
var request = require('request');
var apiurl = "externalserverurl:6080";
var options = {
"regid" : "username",
"password" : "password",
"uri" : apiurl,
"registrar_domain" : "mydomain.com",
"lang" : "en",
json: true,
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'User-Agent': 'request'
}
};
function callback(error, response, body) {
if (!error && response.statusCode == 200) {
console.log('body:', body);
} else {
console.log('error', error, response && response.statusCode);
}
}
request(options, callback);
As #kay already mentioned, errorcode 401 means that your request is unauthorized. Given that there are a lot of different possible authentication methods (basic auth, digest auth, OAuth, you name it), you should refer to your target server and clarify which auth method you should use before trying to actually modify your code.
You could also check the response body, it could contain some hints about what exactly the server expects but doesn't receive.
I'm using a forEach loop to make a request to two different paths, but, although it does console.log() both bodyResponses, it gives error when trying to save it to render "index.ejs" with its value. (index.ejs is the template I wanna render):
manyPaths.forEach(function (element){
var signature = crypto.createHmac('sha256', apiSecret).update(verb + element.path + expires).digest('hex');
var headers = {
'content-type' : 'application/json',
'Accept': 'application/json',
'X-Requested-With': 'XMLHttpRequest',
'api-expires': expires,
'api-key': apiKey,
'api-signature': signature
};
const requestOptions = {
headers: headers,
url:'https://testnet.bitmex.com'+element.path,
method: verb
};
request(requestOptions, function(error, response, bodyResponse) {
if (error) {
console.log(error);
} else {
console.log(bodyResponse);
bodyResponse=JSON.parse(bodyResponse);
res.render("index", {bodyResponse:bodyResponse});
}
});
});
it does console.log both responses, but I get this error for render():
Error: Can't set headers after they are sent.
You can respond to a HTTP request only ONCE. So in your FOR loop, the first response is sent,and the connection is closed, and when it comes to the second iteration it fails with the error you see.
You have to wait for both calls to complete in parallel, and then kick of a function to send the response .
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);
I'm using NodeJS to call the new MailChimp 3.0 API in order to add an email to a list. While I can get it working via POSTman, I'm having a hard time with Node's http:
var http = require('http');
var subscriber = JSON.stringify({
"email_address": "test#test.com",
"status": "subscribed",
"merge_fields": {
"FNAME": "Tester",
"LNAME": "Testerson"
}
});
var options = {
host: 'https://us11.api.mailchimp.com',
path: '/3.0/lists/<myListID>/members',
method: 'POST',
headers: {
'Authorization': 'randomUser myApiKey',
'Content-Type': 'application/json',
'Content-Length': subscriber.length
}
}
var hreq = http.request(options, function (hres) {
console.log('STATUS CODE: ' + hres.statusCode);
console.log('HEADERS: ' + JSON.stringify(hres.headers));
hres.setEncoding('utf8');
hres.on('data', function (chunk) {
console.log('\n\n===========CHUNK===============')
console.log(chunk);
res.send(chunk);
});
hres.on('end', function(res) {
console.log('\n\n=========RESPONSE END===============');
});
hres.on('error', function (e) {
console.log('ERROR: ' + e.message);
});
});
hreq.write(subscriber);
hreq.end();
Rather than getting even some sort of JSON error from Mailchimp, however, I'm getting HTML:
400 Bad Request
400 Bad Request
nginx
Is it clear at all what I"m doing wrong here? It seems pretty simple, yet nothing I've tried seems to work.
A few additional thoughts:
While http's options have an "auth" property, I'm using the headers instead to ensure the authorization is sent without the encoding (as mentioned here). Still, I've also tried with the "auth" property, and I get the same result.
I'm actually making this call from inside an ExpressJS API (my client calls the Express API, that calls the above code - I've edited all that out of this example for simplicity). That's why my variables are "hres" and "hreq", to distinguish them from the "res" and "req" in Express. Is there any reason that could be the issue?
As mentioned above, I am able to get successful results when using POSTman, so I at least know my host, path, list ID, and API key are correct.
It turns out this had a very simple solution: the "host" property of the options object needed to have only the domain name. IE, remove the "https://" protocol:
var options = {
host: 'us11.api.mailchimp.com',
path: '/3.0/lists/<myListID>/members',
method: 'POST',
headers: {
'Authorization': 'randomUser myApiKey',
'Content-Type': 'application/json',
'Content-Length': subscriber.length
}
}
Try this , its working fine for Me.
var request = require('request');
function mailchimpAddListCall(email, cb){
var subscriber = JSON.stringify({
"email_address": email,
"status": "subscribed"
});
request({
method: 'POST',
url: 'https://us13.api.mailchimp.com/3.0/lists/<Your list id>/members',
body: subscriber,
headers:
{
Authorization: 'apikey <your Mailchimp API key>',
'Content-Type': 'application/json'
}
},
function(error, response, body){
if(error) {
cb(err, null)
} else {
var bodyObj = JSON.parse(body);
console.log(bodyObj.status);
if(bodyObj.status === 400){
cb(bodyObj.detail, null);
}
var bodyObj = JSON.parse(body);
cb(null, bodyObj.email_address +" added to list.");
}
});
}
request is a node module, that you'll need to install into your package.json. npm install --save request
You can use the auth properties just fine with API v3, but if you're getting a 400, that's not the problem. The body of the 400 Error should provide more detailed information, but one thing that jumps out immediately: MailChimp doesn't allow fake or fake-looking emails to be added to lists (like test#test.com), so I'd try a real address and see if that works for you.