具有Microsoft边缘和事件源的无效 CORS



我刚刚建立了一个全新的项目,我想使用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 }) + 'nn');
}, 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/'

我不明白为什么它不起作用。填充物可能有问题吗?我没有正确导入它吗?

多谢!

我建议你改用event-source-polyfill。请将 polyfill 的事件源包含在您的页面中,如下所示的代码(删除以前的事件源和事件源-polyfill js 文件(:

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

它适用于IE 11和我这边的Edge。

最新更新