【问题标题】:nodejs - get request body like php's file_get_contentsnodejs - 获取请求正文,如 php 的 file_get_contents
【发布时间】:2021-11-10 05:09:56
【问题描述】:

在我的 nodejs 代码中,我使用 http 模块来获取 HTTP 请求和对用户的响应。我想采用 request 正文,我希望它是 JSON。

参考this link,我申请我的代码如下:

var http = require("http")
var server = http.createServer(function(request, response) {

    console.log("method: " + request.method)
    console.log("url: " + request.url)
    console.log("headers: " + request.headers)

    var body = []

    request.on("error", function(error) {

        console.log("Incoming request error: " + error)

    }).on("data", function(chunk) {

        body.push(chunk)

    }).on("end", function() {

        var content = Buffer.concat(body).toString

        console.log("request body: " + content)
        response.end("IP: " + request.connection.remoteAddress + "<br>" + content)

    })

}).listen(PORT, function() {
    console.log((new Date()) + " Server is listening on port " + PORT)
})

我尝试在终端中使用以下命令测试上面的代码:

curl -d '{"MyKey":"My Value"}' -H "Content-Type: application/json" http://myserverdomain.com:PORT

但反应不是我所期望的 ({"MyKey":"My Value"})!相反,它是一个我不知道它来自哪里的代码 sn-p。见下文:

IP: <MY_IP_ADDRESS><br>function (encoding, start, end) {
  encoding = String(encoding || 'utf8').toLowerCase();

  if (typeof start !== 'number' || start < 0) {
    start = 0;
  } else if (start > this.length) {
    start = this.length;
  }

  if (typeof end !== 'number' || end > this.length) {
    end = this.length;
  } else if (end < 0) {
    end = 0;
  }

  start = start + this.offset;
  end = end + this.offset;

  switch (encoding) {
    case 'hex':
      return this.parent.hexSlice(start, end);

    case 'utf8':
    case 'utf-8':
      return this.parent.utf8Slice(start, end);

    case 'ascii':
      return this.parent.asciiSlice(start, end);

    case 'binary':
      return this.parent.binarySlice(start, end);

    case 'base64':
      return this.parent.base64Slice(start, end);

    case 'ucs2':
    case 'ucs-2':
    case 'utf16le':
    case 'utf-16le':
      return this.parent.ucs2Slice(start, end);

    default:
      throw new TypeError('Unknown encoding: ' + encoding);
  }
}

您能告诉我代码中的问题吗?还有为什么返回的是上面的sn-p代码而不是{"MyKey":"My Value"}

非常感谢。

编辑1:

我刚刚在终端中尝试了更详细的命令,但仍然没有运气。

curl -H "Content-Type: application/json" -X POST -d '{"My key":"My value"}' http://myserverdomain.com:PORT

【问题讨论】:

    标签: node.js http request file-get-contents


    【解决方案1】:

    我刚刚发现了问题,在:var content = Buffer.concat(body).toString!!一定是var content = Buffer.concat(body).toString()!我错过了最重要的部分()

    谢谢大家

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-02-13
      • 1970-01-01
      • 1970-01-01
      • 2011-11-13
      • 2018-06-07
      • 2016-06-21
      • 1970-01-01
      相关资源
      最近更新 更多