node.js - 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');
});
请帮我找出它发生的原因。
解决方案
您需要在 app.js 中添加标头。
app.use(function (req, res, next) {
res.header("Access-Control-Allow-Origin", "http://localhost:3001");
next();
});
推荐阅读
- vba - 图表会减慢我在大型 Excel 文件中的计算速度吗?
- php - PHP 表单 - 发送到用户多选地址的电子邮件
- google-cloud-platform - 配置防火墙规则后特定端口打开|过滤
- angular - 如何从模型函数中获取值并在角度 6 中传递 url 上的值
- jenkins - Jenkins 作业配置更改
- c# - 读取文件/文件夹可用性状态
- java - Jmeter响应数据:java.io.IOException:过早的EOF
- elasticsearch - ElasticSearch如何保证所有词都参与搜索
- javascript - 如何在html中获取数组中固定条目的下一个条目
- javascript - Angular - 单元测试主题()?