nodejs post请求抛出TypeError
nodejs http post request throws TypeError
我想做一个简单的服务器,使用google oauth(没有express和passportjs,因为我想研究交换的数据)。
当我的程序试图向google发送post请求时,nodejs抛出:
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(JSON.stringify(res));
当您编写响应或请求时。它应该包含字符串所以你需要把它改成
response.write(querystring.stringify(res));
或
response.write(JSON.stringify(res));
相关文章:
- ajax请求的顺序总是不同的
- TypeError:无法读取属性'推'未定义的JavaScript
- Meteor如何接收HTTP请求
- 有没有一种方法可以防止img get请求使用css或js发生
- 从ajax请求中获取javascript对象
- 未捕获的TypeError无法读取未定义的属性socialsharing
- 扩展SVGTextElement时出现Typescript Uncaught TypeError
- JSONP请求返回结果,但也触发error_callback
- 在localhost Dev Box上测试JSONP请求的最佳方式
- TypeError:在不兼容的接收器nodejs上调用了方法Uint8Array.length
- Ajax请求文档就绪会导致jquery加载缓慢
- MockJax没有在JavaScript应用程序中发送对我AJAX请求的响应
- 正在传递JSONP标头's数据参数到另一个文件中的AJAX请求
- 在openshift node js应用程序中获取请求
- TypeError:请求路径包含未转义的字符
- nodejs post请求抛出TypeError
- TypeError:这个.$的状态为空.ajax请求
- TypeError: undefined不是一个函数GET请求/数据库调用
- 道场'TypeError:无法读取属性'style'为null的'发送xhrPost请求
- 如何使一个https请求与Node.js?-我的脚本在http.get中产生TypeError