如题,在使用node.js进行http请求时,出现如下报错:
The “chunk” argument must be of type string or an instance of Buffer or Uint8Array. Received an instance of Object
编辑
原代码如下:
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