JSON过长,http.request发送POST请求,报错Unexpected end of JSON input
错误是因为JSON太长,没有接收完所有的响应内容造成的
原来的代码
const http = require('http');
let data = {method:'hello'}
let content = JSON.stringify(postData);
let options = {
hostname:'127.0.0.1',
port:80,
path: '/',
method:'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': Buffer.byteLength(content)
}
}
function getPromise(content,options){
return new Promise(function(resolve, rej) {
let request = http.request(options, (res) => {
res.on('data', (chunk) => {
resolve(JSON.parse(chunk));
});
});
request.write(content);
request.end();
})
}
getPromise(content,options)
因为请求的JSON长度比较长,这样读的内容不全,会报SyntaxError: Unexpected end of JSON input,修改函数:
function getPromise(content,options){
return new Promise(function(resolve, rej) {
let chunks = [];
let request = http.request(options, function (res) {
res.on('data', (chunk) => {
chunks.push(chunk);
}).on('end', () => {
let data = Buffer.concat(chunks);
const json = JSON.parse(data);
resolve(json)
});
});
request.write(content);
request.end();
})
}
getPromise(content,options)
这样就能获取完整数据了
当使用Node.js的http.request发送POST请求时,如果JSON数据过长,可能会遇到'Unexpected end of JSON input'错误。错误的根本原因是未能完全接收响应内容。通过调整代码以确保读取完整数据,可以解决此问题。
2万+

被折叠的 条评论
为什么被折叠?



