Javascript nodejs http post请求引发TypeError
我正在尝试制作一个使用GoogleOAuth的简单服务器(没有express和passportjs,因为我想研究交换的数据) 当我的程序试图向google发送post请求时,nodejs抛出:Javascript nodejs http post请求引发TypeError,javascript,node.js,http,post,oauth-2.0,Javascript,Node.js,Http,Post,Oauth 2.0,我正在尝试制作一个使用GoogleOAuth的简单服务器(没有express和passportjs,因为我想研究交换的数据) 当我的程序试图向google发送post请求时,nodejs抛出: http.js:593 throw new TypeError('first argument must be a string or Buffer'); 我已经检查并确保查询和选项中的所有参数都是字符串,但错误仍然存在。我会错过什么 这是我的密码: // Load the http module to
http.js:593 throw new TypeError('first argument must be a string or Buffer');
我已经检查并确保查询和选项中的所有参数都是字符串,但错误仍然存在。我会错过什么
这是我的密码:
// Load the http module to create an http server.
var http = require('http');
var url = require('url');
var fs = require('fs');
var querystring = require('querystring');
var content;
fs.readFile('./test.html',function(err,data){
content = data;
});
// Configure our HTTP server to respond with Hello World to all requests.
var server = http.createServer(function (request, response) {
response.writeHead(200, {"Content-Type": "text/html"});
var path = url.parse(request.url).pathname;
var query = querystring.parse(url.parse(request.url).query);
var code;
if (query!=null) {
code = query.code;
};
if ('/auth/google/callback'==path){
var data = querystring.stringify({
'code': ''+code,
'client_id': 'id',
'client_secret': 'secret',
'redirect_uri': 'http://localhost:8999/auth/google/code/callback',
'grant_type': 'authorization_code'
});
var options = {
hostname: 'accounts.google.com',
port:'80',
path: '/o/oauth2/token',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': ''+data.length
}
};
debugger;
var post = http.request(options, function(res){
response.write(res);
response.end();
});
debugger;
post.write(data);
debugger;
post.end();
}
else if (path=='/auth/google/code/callback'){
console.log(request.headers);
console.log(request.url);
}
else response.end(content);
console.log(request.headers);
console.log(request.url);
});
// Listen on port 8000, IP defaults to 127.0.0.1
server.listen(8999);
// Put a friendly message on the terminal
console.log("Server running at http://127.0.0.1:8000/");
非常感谢,我想问题是当你说
response.write(res); //it needs a string
我认为,res
是这里的一个对象
试一试
当您编写响应或请求时。它应该包含字符串,所以您需要将其更改为
response.write(querystring.stringify(res));
或
你什么时候发出post请求?post.end(),我想,是在发送请求的时候。我想你说的是
response.write(res)
这里res是一个对象请参见console.log(typeof(res))
。非常感谢Mritunjay,愚蠢的我,内容是一个json对象。你找到问题的解决方案了吗?谢谢你的回答,问题出在回复上。按你说的写。但是,似乎res body实际上是一个重定向消息的html,而不是Json,所以Json.stringify在这里不起作用。@MikeNQ ok没有问题,那么让这个问题打开吧。
response.write(querystring.stringify(res));
response.write(JSON.stringify(res));