vue EventSource使用及配置请求头、webpack代理配置教程
更新时间:2025年12月17日 15:37:10 作者:我的心巴
EventSourcePolyfill是EventSource封装的一个方法,可以配置请求头,安装依赖后,不需要加请求头时直接使用,需要加请求头时可以自定义请求头,基于webpack的vue项目,需要配置代理以解决跨域问题,设置devServer的compress属性为false以实时收到EventSource的消息
EventSourcePolyfill 是EventSource封装的一个方法,可以配置请求头。
官方API:https://developer.mozilla.org/en-US/docs/Web/API/EventSource
一、安装依赖
npm install eventsource npm install event-source-polyfill
二、不需要加请求头时
const eventSource = new EventSource(url); //我是在vue项目里,普通请求用的axios;这里的url可以直接写接口路径,baseUrl会直接使用axios的baseUrl
eventSource.onopen = function (e) {
console.log(e, "连接打开时触发");
};
eventSource.onmessage = function (e) {
console.log(e);
};
eventSource.onerror = function (e) { //断开连接及后端返回错误信息均会触发
eventSource.close(); // 关闭连接
};三、需要加请求头时
<script>
import { EventSourcePolyfill } from 'event-source-polyfill'
export default {
methods: {
eventSource () {
const _this = this, eventSource = new EventSourcePolyfill(url, {
heartbeatTimeout:300000, //超时时间,毫秒为单位,以5分钟为例
headers: {
'请求头名称': '请求头值'
}
});
eventSource.onopen = function (e) {
console.log('onopen', e);
};
eventSource.onmessage = function (e) {
console.log('onmessage', e);
};
eventSource.onerror = function (e) {
console.log('onerror', e);
_this.$message.error('连接失败');
eventSource.close(); // 关闭连接
};
}
}
}
</script>四、webpack代理配置
基于webpack的vue项目一般都会配置代理,用于解决接口请求的跨域问题,若想实时收到EventSource的消息,而不是在最后一口气收到,需要配置 vue.config.js里的devServer,设置devServer的compress属性为false
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
相关文章
使用vue和datatables进行表格的服务器端分页实例代码
本篇文章主要介绍了使用vue和datatables进行表格的服务器端分页实例代码,具有一定的参考价值,感兴趣的小伙伴们可以参考一下2017-06-06
vue.js自定义组件实现v-model双向数据绑定的示例代码
这篇文章主要介绍了vue.js自定义组件实现v-model双向数据绑定的示例代码,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧2020-01-01


最新评论