首页 > 解决方案 > apache2上socket.io和nodejs的CORS头错误

问题描述

我只是在 laravel 中实现 socket.io。但我收到Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:3001/socket.io/?EIO=3&transport=polling&t=MM9_PhA. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).错误。

下面是我的 node.js 文件:

var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);

var Redis = require('ioredis');
var redis = new Redis();
redis.subscribe('test-channel', function (err, count) {
});
redis.on('message', function (channel, message) {
    io.set('origins', 'http://localhost:3001');
    console.log('Message Recieved: ' + message);
    message = JSON.parse(message);
    io.emit(channel + ':' + message.event, message.data);
});
http.listen(3001, function () {
    io.set('origins', 'http://localhost:3001');
    console.log('Listening on Port 3001');
});

请帮我找出它发生的原因。

标签: node.jswebsocketsocket.io

解决方案


您需要在 app.js 中添加标头。

app.use(function (req, res, next) {
   res.header("Access-Control-Allow-Origin", "http://localhost:3001");

  next();
});

推荐阅读