[英]CORS error when trying to connect to the server via socket.io
I'm getting 我越来越
Access to XMLHttpRequest at 'http://localhost:4000/socket.io/?EIO=3&transport=polling&t=Moz5j40' from origin 'http://localhost:3000' has been blocked by CORS policy: The 'Access-Control-Allow-Origin' header has a value 'http://localhost:3000/' that is not equal to the supplied origin.
error when trying to access a websocket. 尝试访问WebSocket时发生错误。
I've tried setting up the cors package and setting up 我尝试设置cors软件包并进行设置
io.origins("*:*");
backend: 后端:
import express from "express";
import cors from "cors";
import _http from "http";
import _io from "socket.io";
const app = express();
const http = _http.createServer(app);
const io = _io(http);
io.origins("*:*");
app.use(
cors({
credentials: true,
origin: "http://localhost:3000/"
})
);
io.on("connection", socket => {
console.log("a user connected");
});
app.listen(4000, () => {
console.log("Listening on port 4000!");
});
frontend: 前端:
import React, { useState } from "react";
import openSocket from "socket.io-client";
const socket = openSocket(process.env.REACT_APP_API_URL as string);
function subscribeToTimer(
cb: (err: Error | null, timestamp: number) => void
): void {
socket.on("timer", (timestamp: number) => cb(null, timestamp));
socket.emit("subscribeToTimer", 1000);
}
export { subscribeToTimer };
const App: React.FC = () => {
const [timestamp, setTimestamp] = useState(-1);
subscribeToTimer((_err, tp) => setTimestamp(tp));
return <div className="App">Current timestamp {timestamp}</div>;
};
export default App;
I expect to see "a user connected" message in the terminal. 我希望在终端中看到“用户已连接”消息。
添加一个将CORS标头添加到* ...的中间件,不仅是源,而且是方法
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.