【发布时间】:2021-05-05 03:12:28
【问题描述】:
我正在尝试将客户端连接到服务器套接字,但出现此错误。
Access to fetch at 'http://localhost:9999/socket.io/?EIO=4&transport=polling&t=NTQGzyP&b64=1' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
我查看了类似问题的答案并尝试了它们,没有任何变化。这包括使用 WebApp.rawConnectHandlers 设置标题和设置 cors 选项无济于事。我花了很多时间复制其他人提到的不同解决方案,但似乎没有什么不同。
我尝试在创建服务器之前和之后添加标头。
客户
const io = require("socket.io-client")
const socket = io.connect("http://localhost:9999/")
服务器
import {Meteor} from 'meteor/meteor';
import http, * as Http from 'http';
import {Socket} from 'socket.io';
import {WebApp} from "meteor/webapp";
Meteor.startup(() => {
// Server
const server: Http.Server = http.createServer();
WebApp.rawConnectHandlers.use(function (req, res, next) {
res.setHeader("Access-Control-Allow-Origin", "*");
return next();
});
const io = require('socket.io')(server);
io.on('connection', (socket: Socket)=>{
socket.on('hello',(data)=>{
console.log('HELLO BISH')
console.log(data.text)
})
})
// Start server
try {
server.listen(9999);
} catch (e) {
console.error(e);
}
});
允许连接的正确方法是什么?
【问题讨论】:
标签: javascript node.js typescript meteor socket.io