原本的需求是,后端返回一个流,并向流中传送数据,前端将后端向流中传送的数据一点一点读出来
后端代码如下
@PostMapping("/streaming-text")
public StreamingResponseBody stream() {
return out -> {
for (int i = 0; i < 10; i++) {
out.write(("Message " + i + "\n").getBytes());
out.flush();
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
}
前端请求如下
axios.post('http://localhost:8080/streaming-text', {
// specify the response type as stream
responseType: 'stream'
})
.then(response => {
const stream = response.data
stream.on('data', chunk => {
console.log(new TextDecoder().decode(chunk))
})
stream.on('end', () => {
console.log('Stream ended')
})
})
.catch(error => {
console.error(error)
})
结果报错
TypeError: stream.on is not a function
说stream.on不是一个方法,用fetch就可以顺利读取出来,但是axios就不行,请问该如何使用axios完成