On a Node server, I am trying to validate a Google user but it always returns with a "Bad Request". What is wrong in my code?
var post_data = querystring.stringify({
'alt': 'json',
'access_token': <token from REST API params>
});
var post_options = {
host: 'www.googleapis.com',
port: '443',
path: '/oauth2/v1/userinfo',
method: 'GET',
headers: {
'Content-Length': Buffer.byteLength(post_data)
}
};
var post_req = https.request(post_options, function (result) {
if (result.statusCode == 200) {
result.on('data', function (chunk) {
//Valid user stuff
});
}
else {
//Invalid user stuff
}
});
post_req.write(post_data);
post_req.end();
The scenario here is that my client app is a chrome extension that successfully gets a token. The token is passed to my REST API hosted on the Node server. I try to replay that token to authenticate the Google user. (Note that if I use the token on the Chrome extension to make the same request, it succeeds and I get the profile information! It's only the request on the Node server that fails.) Help me! Please?
The problem is that you are:
Using the property host instead of hostname
Providing the port parameter (not sure about this one, but it will work without it)
Method should be POST, not GET
So, your new post_options object should be:
var post_options = {
hostname: 'www.googleapis.com',
path: '/oauth2/v1/userinfo',
method: 'POST',
headers: {
'Content-Length': Buffer.byteLength(post_data)
}
};
If you want to make it easier on yourself you could use a module such as google-auth-library or google-sign-in.
Related
guys, I am trying to authorize myself to Mailchimp API but its give me 401 error can any find a problem in the code I am using request
app.post('/',function(req,res){
var firstname=req.body.first;
var lastname= req.body.last;
var email= req.body.email;
var options={
url:'https://us10.api.mailchimp.com/3.0/lists/47303a99f3',
method: 'POST',
header:{
'Authorization':'Basic 55adfb745d93168c37966fbd734e46d1-us10'
}
};
request(options,function(e,r,b){
if(e){
console.log(e);
}else if(r){
console.log(r.statusCode);
}
});
});
There is an issue with your options object.
The request module expects the headers attribute in options instead of header attribute. Hence your authorization header is not getting identified on the server side.
It should work if you update your options to:
var options={
url:'https://us10.api.mailchimp.com/3.0/lists/47303a99f3',
method: 'POST',
headers:{
'Authorization':'Basic 55adfb745d93168c37966fbd734e46d1-us10'
}
};
Reference.
I have one problem with HTTP GET/POST request.
When I use the DHC/Postman, send the parameters to the URL + endpoint, works perfectly. 200 is returned.
But with code, like my example, show one 401 error.
I have searched about that and the problem is with the auth, not sure, see... Maybe is the same.
With this explanation, need to set the Authorization, I think. But the problem is when I access the site, the auth is automatic, see:
My code:
var jsonObject = JSON.stringify({ "UserName": login});
// prepare the header
var postheaders = {
'Content-Type' : 'application/json',
'Content-Length' : Buffer.byteLength(jsonObject, 'utf8')
};
// the post options
var optionspost = {
host: "xxxxxxxxxx.com",
// path: '/Home/endpoint', //send the data for the endpoit with Postma works fine
method: 'POST',
headers : postheaders
};
console.info('Options prepared:');
console.info(optionspost);
console.info('Do the POST call');
// do the POST call
var reqPost = http.request(optionspost, function(res) {
console.log("statusCode: ", res.statusCode);
// uncomment it for header details
// console.log("headers: ", res.headers);
res.on('data', function(d) {
console.info('POST result:\n');
process.stdout.write(d);
console.info('\n\nPOST completed');
});
});
// write the json data
reqPost.write(jsonObject);
reqPost.end();
reqPost.on('error', function(e) {
console.error(e);
});
Obs.: This website it's from my Company (.NET) and is Integrated with IIS (Active Directory login users for authenticate), when I access, automatically is logged... I really don't know how to solve this.
Obs II.: I Try to use one anonymous new tab and use DHC online, and my post doesn't work. This application just works inside network company and with Client side (Using postman with my computer).
Obs III.: The request is from Server and the login from my server have all permissions to access this site, and when I request, is like I'm anonymous, but if I did the same with REST Client/Postman, works perfectly. I need that it works with http request from my Server.
You can use a module like ntlm-webapi which will allow you to use NTLM auth. That way the request will go through. Just make sure the user you use is authorized for that server.
var Request = require('ntlm-webapi');
var request = new Request({
url: "http://some.restful.api.org/you/want/to/call",
username: 'username',
password: 'password',
domain: 'company_domain'
});
request.get(function(err, result){
if (err) console.log (err);
console.log (result);
});
It seems that you forgot to add the Authorization header in your code
// prepare the header
var postheaders = {
'Authorization' : 'Negotiate '+ yourAccessKey,
'Content-Type' : 'application/json',
'Content-Length' : Buffer.byteLength(jsonObject, 'utf8')
};
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.
I have a node.js application using googleapis oauth.
My developer console is set up with two redirect uris: http://i.imgur.com/qraUa4Y.jpg
I can make the initial call to https://accounts.google.com/o/oauth2/auth with the redirect_uri to be either /token or /update
After a successful callback, I attempt to exchange the code for the token with the following code:
var exchangeToken = function (params) {
var post_data = querystring.stringify({
code: params.code,
client_id: credentials.client_id,
client_secret: credentials.client_secret,
redirect_uri: 'https://www.example.org/token', //this line won't work
grant_type: 'authorization_code'
});
var req = https.request({
host: 'www.googleapis.com',
path: '/oauth2/v3/token',
method: 'POST',
port: 443,
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': post_data.length
}
}, function(res) {
res.setEncoding('utf8');
res.on('data', function (chunk) {
console.log('BODY: ' + chunk);
});
});
req.write(post_data);
req.end();
};
If I set the redirect_uri to be /token the call falls, returning
BODY: {
"error": "redirect_uri_mismatch",
"error_description": "Bad Request"
}
But if I change to /update it works. The initial request accepts both urls, but this one fails for /token.
Whats going wrong?
Double-check that what you sent earlier in the authorization request matches what you send in the request to the token endpoint. You can use either URL that you've configured in the API Console but it must be the same in both requests.
Make sure redirect_uri: 'https://www.example.org/token' is same configured on Google Client API with 'Authorized redirect URIs' block.
In my case, it works...!!!
I am trying to post a task in asana with the following node/express function
exports.addTask = function(req, res) {
var url ='/api/1.0/tasks?workspace=' + req.session.workspace_id
var postBase = "app.asana.com";
var options = {
host: postBase,
port: 443,
path: url,
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': 'Bearer ' + JSON.parse(req.session.user).access_token,
}
};
var req2 = https.request(options, function(res2) {
res2.on('data', function(chunk) {
console.log(chunk + "");
});
res2.on('error', function(e){
console.log(e.message);
});
});
req2.end();
}
I get the correct response back from asana which is:
{"data":{"id":8253508011735,"created_at":"2013-10-20T16:17:53.140Z","modified_at":"2013-10-20T16:17:53.140Z","name":"","notes":"","completed":false,"assignee_status":"upcoming","completed_at":null,"due_on":null,"workspace":{"id":1361701377437,"name":"getspur.com"},"assignee":null,"parent":null,"followers":[{"id":1050147548705,"name":"Gorkem Yurtseven"}],"projects":[],"tags":[]}}
but nothing seems to be added in my asana tasks..
ps. I am currently at the Facebook Hackathon in New York,so bring it on!
It could be because the assignee is null, and it's not in any projects - that basically makes it impossible to find (except perhaps via Search?)
Without seeing the post body I'm not sure if that's intentional or just a formatting issue.