【发布时间】:2015-05-05 18:53:44
【问题描述】:
在尝试调试以下 get 请求时,我注意到它返回 undefined,然后运行 response 的代码。
configs 是一个定义了所有参数的 json 对象。出于某种原因,我也收到了来自 php 服务器的响应,说授权类型无效或找不到,尽管在调试时它从配置文件传递了正确的参数。
如何更正我的代码?
var http = require("http");
var querystring = require("querystring");
var _ = require("underscore");
apiCaller = {};
apiCaller.token = null;
var server=http.createServer(function(req,res){});
server.listen(8080);
apiCaller._get = function (context, config, fn) {
// request to obtain our oauth token
var options = {
method: "GET",
hostname: config.host,
client_id: config.clientId,
client_secret: config.clientSecret,
grant_type: config.grant_type,
path: "/my/path/to/token",
headers : {
'Content-Type': "application/json",
'Accept': "application/json"
}
};
var callback = function(response) {
console.log('STATUS: ' + response.statusCode);
console.log('HEADERS: ' + JSON.stringify(response.headers));
var str = '';
//another chunk of data has been recieved, so append it to `str`
response.on('data', function (chunk) {
str += chunk;
});
// error response
response.on("error", function (error) {
if ( !context ) {
console.error("Something went wrong with the api response.");
return;
}
context.done(new Error("Something went wrong with the api response."));
});
//the whole response has been recieved, so we just print it out here
response.on('end', function () {
apiCaller.token = JSON.parse(str).access_token;
// we want to stop the request if token is not correct
if ( !apiCaller.token || apiCaller.token === undefined || apiCaller.token === null ) {
if ( !context ) {
console.error("Something went wrong with the token. Wrong token! Token: %s", apiCaller.token);
return;
}
console.error("Token: %s", apiCaller.token);
context.done(new Error("Something went wrong with the token. Wrong token!"));
}
});
};
var request = http.request(options, callback);
request.on('error', function(e) {
console.log('problem with request:');
});
request.end();
};
【问题讨论】:
-
grant_type 不应该作为查询字符串作为路径的一部分吗?我没有在节点文档中注意到这样的请求选项。
-
@Molda 我不确定。那么client_id和client_secret呢?
-
这些都不是 http.request 的选项。你可以查看nodejs.org/api/http.html#http_http_request_options_callback
-
尝试将您的路径更改为“/my/path/to/token?grant_type=type&client....等。
-
不幸的是仍然得到相同的响应。
标签: node.js