带有Microsoft Edge和EventSource的无效CORS

时间:2018-09-01 13:37:10

标签: cors microsoft-edge eventsource

我刚刚建立了一个新的项目,并且想使用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);
};

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

//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 个答案:

答案 0 :(得分:1)

我建议您改用 event-source-polyfill 。请像下面的代码一样将polyfill的事件源包括到您的页面中(删除先前的eventsource和eventsource-polyfill js文件):

require('../node_modules/event-source-polyfill/src/eventsource.js')

它在IE 11和Edge上都可以使用。