【问题标题】:nodejs http post request throws TypeErrornodejs http post请求抛出TypeError
【发布时间】:2014-09-01 15:57:14
【问题描述】:

我正在尝试制作一个使用 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/");

非常感谢,

【问题讨论】:

  • 你什么时候发帖请求?
  • post.end(),我认为是发送请求的时间。
  • 我想你是在说response.write(res) 这里 res 是一个对象见console.log(typeof(res))
  • 非常感谢 Mritunjay,我真傻,内容是一个 json 对象。
  • 你的问题解决了吗?

标签: javascript node.js http post oauth-2.0


【解决方案1】:

我认为问题在于你说的时候

response.write(res); //it needs a string

我认为res 是这里的一个对象。

试试

response.write(JSON.stringify(res));

【讨论】:

  • 感谢您的回答,正如您所说,问题出在 response.write 上。但是,似乎 res 正文实际上是重定向消息的 html 而不是 Json,因此 JSON.stringify 在这里不起作用。
  • @MikeNQ 好的,没有问题,然后让这个问题打开。
【解决方案2】:

当您编写响应或请求时。它应该包含字符串,因此您需要将其更改为

response.write(querystring.stringify(res)); 

response.write(JSON.stringify(res));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-07-07
    • 2015-06-26
    • 1970-01-01
    • 2015-12-31
    • 2017-03-12
    • 1970-01-01
    • 2013-11-16
    相关资源
    最近更新 更多