无效的oauth2令牌请求

我正在开发一个需要使用Google进行身份validation的节点应用程序。 当我申请一个令牌时, https : //accounts.google.com/o/oauth2/token回应:

error: 400 { "error" : "invalid_request" } 

我已经试过用curl做同样的请求,并且收到了同样的错误,所以我怀疑我的请求有问题,但是我不知道是什么。 我粘贴了下面的代码:

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

我已经三重检查,以确保我提交的所有数据是正确的,我仍然得到相同的错误。 我能做些什么来进一步debugging呢?

事实certificate,request.js(https://github.com/mikeal/request)不会自动在头中包含内容长度。 我手动添加它,它在第一次尝试。 我粘贴下面的代码:

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

从这里如何在node.js中发出HTTP POST请求? 你可以使用querystring.stringify来转义请求参数的查询string。 另外,您最好为POST请求添加'Content-Type': 'application/x-www-form-urlencoded'

在这里发布从token_request var.that产生的最后一个string,可能有错误。 或者可能是validation码过期或者没有正确添加到URL中。 通常代码中有'/',需要转义。