前端用axios组件的流模式调用node.js接口,node.js 接口如何控制每次返回的数据都是一个完整的json字符串, json串是不等长的?
比如:
第一次返回:
{"content":"你"}
第二次返回:
{"content":"好吗"}
第三次返回:
{"content":"?"}
通过这个转换一下:
const server = http.createServer((req, res) => {
const data = {
name: "John",
age: 28,
city: "New York"
};
res.setHeader("Content-Type", "application/json"); //指定内容类型
res.end(JSON.stringify(data)); //转换
});
在Node.js中,可以通过设置响应头来控制每次返回的数据都是一个完整的JSON字符串。具体来说,可以设置响应头的Content-Type为application/json,并且使用response.write方法来写入JSON字符串,最后使用response.end方法结束响应。
例如,下面是一个简单的Node.js接口示例:
http.createServer((request, response) => {
response.writeHead(200, { 'Content-Type': 'application/json' });
let data = '';
if (request.url === '/api') {
// 模拟分多次返回数据 response.write('{"content":"你"}');
response.write('{"content":"好吗"}');
response.write('{"content":"?"}');
response.end();
} else {
response.end(JSON.stringify({ message: 'Not Found' }));
}
}).listen(3000);
在这个示例中,我们设置了响应头的Content-Type为application/json。然后,我们使用response.write方法分多次写入JSON字符串,最后使用response.end方法结束响应。
注意,虽然我们分多次写入JSON字符串,但是客户端收到的仍然是一个完整的JSON字符串。因为我们设置了响应头的Content-Type为application/json,客户端会自动将多个JSON片段合并成一个完整的JSON字符串。