vue EventSource使用及配置请求头、webpack代理配置

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值