Microsoft Edge和EventSource存在无效的跨域资源共享问题

3
我刚刚创建了一个全新的项目,想要使用EventSource。我希望它能与主流浏览器兼容,包括Edge。但是由于Edge不支持EventSource,所以我需要安装一个polyfill
我的客户端是一个运行在http://localhost:8080/地址上的vue cli应用程序。我在main.js文件中添加了以下代码:
// Client - main.js

import '@babel/polyfill'
import Vue from 'vue'
import './plugins/vuetify'
import App from './App.vue'
import router from './router'
import store from './store'
import './registerServiceWorker'

//Not sure if this one is necessary, so far I got the same result with and without it.
require('../node_modules/eventsource/lib/eventsource.js');

//polyfill for Edge
require('../node_modules/eventsource/lib/eventsource-polyfill.js'); 


Vue.config.productionTip = false

new Vue({
  router,
  store,
  render: h => h(App)
}).$mount('#app')

var source = new EventSource(
  'http://localhost:3000/',
  {withCredentials: true}
);

source.onmessage = function(e) {
    var jsonData = JSON.parse(e.data);
    console.warn("My message: " + jsonData.msg);
};

然后,以下代码在我的Node.js服务器上运行,网址为http://localhost:3000/:

//Server

var express     = require("express"),
    app         = express(),
    bodyParser  = require('body-parser');

app.use(express.static(__dirname + '/'));
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

app.get('*', function(req, res){
    res.writeHead(200, {
      'Connection': 'keep-alive',
      'Content-Type': 'text/event-stream',
      'Cache-Control': 'no-cache',
      "Access-Control-Allow-Origin": "http://localhost:8080",
      "Access-Control-Expose-Headers": "*",
      "Access-Control-Allow-Credentials": true
    });

    setInterval(function(){

      const date = new Date();
      const data = date.getTime()

      console.log('writing ' + data);
      res.write('data: ' + JSON.stringify({ msg : data }) + '\n\n');
    }, 1000);
});

var port = 3000;
app.listen(port, function() {
  console.log("Listening at Port " + port);
});

我已经添加了一些CORS头信息,否则EventSource在Chrome上无法正常工作。 上述代码在Chrome、Firefox和Opera上运行良好(每秒钟接收到一条消息)。但是Edge显示以下错误:

SEC7120: [CORS] The origin 'http://localhost:8080' did not find 'http://localhost:8080' in the Access-Control-Allow-Origin response header for cross-origin  resource at 'http://localhost:3000/'

我不明白为什么它不能正常工作。这可能与polyfill有关吗?我没有正确导入它吗?

非常感谢!

1个回答

1
我建议您使用event-source-polyfill。请按照以下代码将polyfill的eventsource包含到您的页面中(删除先前的eventsource和eventsource-polyfill js文件):
require('../node_modules/event-source-polyfill/src/eventsource.js')

在我的电脑上,它在IE 11和Edge中都能正常工作。


“event-source-polyfill” 似乎可以与 {withCredentials} 一起使用,而 “eventsource” 则不行。我的 SSE 现在可以使用 CORS。谢谢! - Tormod Haugene

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接