node.js报错The “chunk“ argument must be of type string or an instance of Buffer or Uint8Array.


如题,在使用node.js进行http请求时,出现如下报错:

The “chunk” argument must be of type string or an instance of Buffer or Uint8Array. Received an instance of Object

img点击并拖拽以移动编辑

原代码如下:

const http = require("http");
const querystring = require("querystring");

const server = http.createServer((req, res) => {
  const method = req.method;
  const url = req.url;
  const path = req.url.split("?")[0];
  const query = req.url.split("?")[1];

  // 设置返回数据格式
  res.setHeader("Content-type", "application/json");

  const resData = {
    method,
    url,
    path,
    query,
  };

  if (method === "GET") {
    res.end(resData); // 这里数据类型为Object类型
  }
});

server.listen(8000);
console.log("OK");

点击并拖拽以移动

response.end()方法接收的参数类型只能是字符串或Buffer

修改办法:

const http = require("http");
const querystring = require("querystring");

const server = http.createServer((req, res) => {
  const method = req.method;
  const url = req.url;
  const path = req.url.split("?")[0];
  const query = req.url.split("?")[1];

  // 设置返回数据格式
  res.setHeader("Content-type", "application/json");

  const resData = {
    method,
    url,
    path,
    query,
  };

  if (method === "GET") {
    res.end(JSON.stringify(resData)); // 这里转换为字符串类型
  }
});

server.listen(8000);
console.log("OK");

点击并拖拽以移动

问题就解决啦~

总结: response.end()方法接收的参数类型只能是字符串或Buffer


文章作者: Nanying
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 Nanying !
评论
  目录