axios使用post请求sse接口
依赖:
"@microsoft/fetch-event-source": "^2.0.1",
"axios": "^1.7.3",
请求函数:
/**请求sse接口
@param url 接口地址
@param method 请求方法 GET POST
@param headers 请求头
@param formData 提交参数 例如: const formData = new URLSearchParams();
formData.append('question', q);
formData.append('tableInfoId', '1');
@param onmessageCall 收到消息回调
@param errorCall 错误回调
*/
const postSSE = (url, headers, formData, onmessageCall, errorCall) => {
fetchEventSource(url, {
method: "POST",
headers: {
'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8', // 设置Content-Type
'Cache-Control': 'no-cache',
'Connection': 'keep-alive',
...headers
},
body: formData.toString(), // 提交URL编码的表单数据
onopen: async (response) => {
// console.log("response.ok", response.ok);
// console.log("response.body", response.body);
let contentType = response.headers.get('content-type');
// console.log("response.content-type", contentType);
if (response.ok) {
if (contentType.startsWith('text/event-stream')) {
return; // 连接成功
} else if (contentType === "application/json;charset=utf-8") {
// 直接读取响应数据
const data = await response.json();
errorCall(data.statusMsg)
} else {
errorCall("接口响应异常");
}
} else if (response.status >= 400 && response.status < 500 && response.status === 429) {
errorCall("响应状态异常:" + response.status);
} else {
errorCall(response.data);
}
},
onclose() {
// 服务器关闭连接时调用
console.log('Connection closed');
},
onmessage: (event) => {
//回调
// console.log("收到信息:", event.data);
onmessageCall(event.data)
},
onerror: (err) => {
//回调
errorCall(err)
}
});
}