原本的需求是,后端返回一个流,并向流中传送数据,前端将后端向流中传送的数据一点一点读出来
后端代码如下
@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完成
不知道你这个问题是否已经解决, 如果还没有解决的话:使用axios来处理流数据需要在请求中设置responseType为stream,并且在响应拦截器中处理流数据。下面是一个示例代码,可以使用axios请求后端流数据并将其一点一点地输出到控制台:
import axios from 'axios';
import { Readable } from 'stream';
axios.post('/streaming-text', null, {
responseType: 'stream'
}).then(response => {
let reader = response.data.getReader();
let decoder = new TextDecoder('utf-8');
let readChunk = function() {
reader.read().then(function(result) {
if (result.done) {
console.log('Stream complete');
return;
}
console.log(decoder.decode(result.value));
readChunk();
});
};
readChunk();
}).catch(error => {
console.error('Stream request failed', error);
});
在这个示例中,我们使用axios对象来请求后端的流数据,并设置responseType为stream以表示响应为流数据。在响应拦截器中,我们使用ReadableStream对象的getReader()方法获取到一个ReadableStreamDefaultReader对象的reader,并使用TextDecoder对象将二进制数据解码为UTF-8字符串。在读取流数据的过程中,我们递归调用readChunk()函数来一点一点地读取数据,直到数据读取完成为止。
“Devil组”引证GPT后的撰写:
将axios的responseType设置为stream,并使用流的方式读取响应数据。以下是一个示例代码,可以将其作为参考:
axios({
method: 'post',
url: 'http://localhost:8080/streaming-text',
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)
})
直接使用axios函数调用,并将responseType设置为'stream'。在得到响应之后,我们可以通过response.data获取到流对象,并对其进行处理。通过监听data事件和end事件,我们可以在流中逐步获取数据,并在结束时得到通知。