vue.js

关注公众号 jb51net

关闭
首页 > 网络编程 > JavaScript > javascript类库 > vue.js > vue EventSource配置请求头、webpack代理配置

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

作者:我的心巴

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

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

您可能感兴趣的文章:
阅读全文