提问人:Saradh Savyasaj 提问时间:11/6/2023 最后编辑:SendETHToThisAddressSaradh Savyasaj 更新时间:11/8/2023 访问量:42
跨域 WebSocket 连接被 CORS 策略阻止
Cross-Origin WebSocket connection blocked by CORS policy
问:
我正在构建一个 Web 应用程序,使用 React 作为客户端和一个 Node.js 服务器,并带有用于 WebSocket 通信的 Socket.io。客户端在 http://localhost:5173 上运行,服务器在 http://localhost:6012 上运行。当我运行此请求时
GET http://localhost:6012/socket.io/?EIO=4&transport=polling&t=OkaxqAF net::ERR_FAILED 200 (OK)
要建立从客户端到服务器的 WebSocket 连接,我遇到以下错误:
访问 XMLHttpRequest “http://localhost:6012/socket.io/?EIO=4&transport=polling&t=OkaxqAG” 来自源的“http://localhost:5173”已被 CORS 策略阻止: 请求的标题上不存在“Access-Control-Allow-Origin”标头 资源。轮询.js:298
我尝试查找错误,这似乎与由于 COR 策略而被服务器阻止的某些请求有关。我已将服务器和客户端上的 URL 列入白名单。我不明白问题到底是什么。
`
import http from "http";
import express from "express";
import dotenv from "dotenv";
import { Server as SocketServer } from "socket.io";
import mongoose from "mongoose";
import jwt from "jsonwebtoken";
import cookieParser from "cookie-parser";
import cors from "cors";
dotenv.config({ path: "./config.env" });
import { User } from "./models/User.js";
import bcrypt from "bcryptjs";
import { authRouter } from "./routes/authRoute.js";
import { profileRouter } from "./routes/profileRouter.js";
import { mediaRouter } from "./routes/mediaRoute.js";
import { userRouter } from "./routes/userRoute.js";
import { chatRouter } from "./routes/chatRouter.js";
import { authenticateUser} from "./functions/authenticateUser.js";
const jwtSecret = process.env.SECRET_KEY;
const app = express();
const server = http.createServer(app);
const io = new SocketServer(server);
app.use(express.static("public"));
//MIDDLEWARES
app.use(express.json());
app.use(cookieParser());
app.use(
cors({
credentials: true,
origin: "http://localhost:5173"
})
);
//DATABASE CONNECTION
const DB = process.env.DATABASE_STRING.replace(
"<password>",
process.env.PASSWORD
);
mongoose
.connect(DB)
.then(() => {
console.log(`DATABASE CONNECTION WAS SUCCESSFULL !`);
})
.catch((error) => {
console.log(error, ` --- this error happened \n`);
});
///WEB SOCKET IMPLEMENTATION
io.on('connection' , (socket) => {
console.log("A new user connected " , socket.id , " --socket.id-- \n")
})
//ROUTES
app.use("/auth", authRouter);
app.use("/profile", profileRouter);
app.use("/media", mediaRouter);
app.use("/users", userRouter);
app.use("/chats", chatRouter);
app.get("/test", (req, res) => {
res.send("<h2> test ok </h2>");
});
app.get("/profile", (req, res) => {
console.log(`get req recieved to the profile endpoint \n`);
const { token } = req.body;
jwt.verify(token, jwtSecret, {}, (err, userData) => {
if (err) throw err;
res.json(userData);
});
});
const port = process.env.PORT;
server.listen(port, () => {
console.log(`app listening on port - ${port} \n`);
});
`
import React, { useState, useEffect } from "react";
import axios, { all } from "axios";
import { extractToken } from "../functions/extractToken";
import { useUser } from "../apis/ContextApi";
import SearchIcon from "@mui/icons-material/Search";
import { useParams } from "react-router-dom";
import { useNavigate } from "react-router-dom";
import { io } from "socket.io-client";
export const ChatPage = () => {
const [enteredUsername, setEnteredUsername] = useState("");
const [userInfoArray, setUserInfoArray] = useState(null);
const { otherUserId } = useParams();
const [loggedInUserMessages, setLoggedInUserMessages] = useState(null);
const [otherUserMessages, setOtherUserMessages] = useState(null);
const [messages, setMessages] = useState(null);
const [allOtherUsers, setAllOtherUsers] = useState([]);
const [allOtherUsersImm, setAllOtherUsersImm] = useState([]);
const [otherUser, setOtherUser] = useState({});
const [sentMessage, setSentMessage] = useState("");
const { user } = useUser();
const navigate = useNavigate();
const userToken = extractToken("jwtToken");
const { id } = useParams();
const handleChatClick = (userId) => {
console.log(
`this chat has these two participants - ${id} and ${userToken} `
);
navigate(`/chats/userId/${userId}`);
};
useEffect(() => {
//render the chat of the loggedinUser and the user with the id -- (otherUserId)
//also render all the chats ie previous chats of the loggedIn User ...
const config = {
headers: {
Authorization: userToken,
},
};
const socket = io("http://localhost:6012", {
withCredentials: true, // You need to include credentials when connecting.
});
socket.on("message", (message) => {
console.log("Received a message:", message);
});
axios
.get(`http://localhost:6012/users/allOtherUsers`, config)
.then((response) => {
console.log(
`response data from the /users/allOtherUsers endpoint --- ${response.data} \n`
);
setAllOtherUsers(response.data);
setAllOtherUsersImm(response.data);
})
.catch((err) => {
console.log(`err happened while fetching allOtherUsers ---\n`);
});
}, []);
useEffect(() => {
const config = {
headers: {
Authorization: userToken,
},
};
axios
.get(`http://localhost:6012/users/otherUser?userId=${id}`, config)
.then((response) => {
console.log(
`response data from the /users/otherUser ( ie the otherUser doc ) --- ${JSON.stringify(
response.data
)} \n`
);
setOtherUser(response.data);
})
.catch((err) => {
console.log(`err happened while fetching otherUser info ---\n`);
});
}, []);
const handleChangeUsername = (ev) => {
ev.preventDefault();
const updatedUserName = ev.target.value;
if (updatedUserName) {
// Filter the users only if there is a search query
const filteredArray = allOtherUsers.filter((element) =>
element.username.includes(updatedUserName)
);
setAllOtherUsers(filteredArray);
} else {
setAllOtherUsers(allOtherUsersImm);
}
/*setEnteredUsername((prevUsername) => {
if (updatedUserName !== prevUsername) {
axios
.post("http://localhost:6012/profile/findUser", {
userToken,
username: updatedUserName,
})
.then((response) => {
console.log(
`response from the findUser endpoint (inside of ChatPage) --- ${JSON.stringify(
response.data
)}\n`
);
setUserInfoArray(response.data);
})
.catch((error) => {
console.error("Error (inside of ChatPage) :", error);
});
return updatedUserName;
}
return prevUsername;
});*/
};
const handleSendingMessage = (ev) => {
ev.preventDefault();
socket.emit("sendMessage", {
message: sentMessage,
recipientId: id,
});
setSentMessage("");
};
return (
<div
id="Chat-Page-Main"
className="w-screen h-screen flex flex-row bg-gray-100"
>
<div
id="Chat-List"
className="w-1/3 flex flex-col bg-gray-200 m-4 rounded-md shadow-lg"
>
<div className="flex rounded-t-md bg-teal h-16 items-center text-center justify-center text-gary-600 text-xl font-semibold">
Search Users
</div>
<div className="flex flex-row w-full p-2">
<input
id="search-chats"
className="w-3/4 h-12 m-2 rounded-md p-2 focus:outline-none bg-gray-300"
onChange={(ev) => handleChangeUsername(ev)}
placeholder="Search for users"
/>
<div
id="SearchIcon-Wrapper-div"
className="flex w-1/6 items-center justify-center p-2 bg-gray-200 rounded-md"
>
<button className="w-full ">
<SearchIcon fontSize="medium" className="text-slate-800" />
</button>
</div>
</div>
<div id="UserList" className="flex w-full flex-col overflow-auto">
{allOtherUsers.map((element) => {
return (
<div
className="w-full flex flex-row sm:m-4 m-2 hover:bg-slate-300 p-2"
key={element._id}
onClick={(e) => handleChatClick(element._id)}
>
<div id="profile-pic" className="h-full w-1/3">
<img
src={element.profilepic}
alt=""
className="h-10 w-10 sm:h-16 sm:w-16 rounded-full"
/>
</div>
<div className="text-xs sm:text-sm m-2 flex flex-col ">
{" "}
<a className="hover-" href={`/users/userId/${element._id}`}>
{element.username}
</a>{" "}
</div>
</div>
);
})}
</div>
</div>
<div
id="Current-Chat"
className="w-2/3 flex flex-col-reverse bg-gray-200 m-4 rounded-md shadow-lg"
>
<form
id="send-message-form"
className="w-3/4 h-16 flex flex-row m-2 justify-between items-center rounded-md"
onSubmit={(ev) => handleSendingMessage(ev)}
>
<input
type="text"
id="send-message-input"
className="bg-white w-3/4 rounded-md p-2 focus:outline-none"
onChange={(e) => setSentMessage(e.target.value)}
placeholder="Type your message..."
/>
<button
id="send-message-button"
className="w-1/4 h-10 bg-blue-600 m-2 rounded-md text-white hover:bg-blue-700"
type="submit"
>
Send
</button>
</form>
<div className="main-chat w-full h-3/4 bg-gray-100"></div>
<div
id="Receiver-Info"
className="w-full bg-gray-200 flex-grow p-4 flex flex-row"
>
{/* Additional receiver info can go here */}
<div
id="OtherUser-ProfileInfo"
className="h-full w-1/2 flex flex-row"
>
<div
id="OtherUser-profilepic-div"
className="h-full w-1/2 flex justify-center items-center"
>
<img
src={otherUser.profilepic}
alt=""
className="h-20 w-20 rounded-full"
/>
</div>
<div id="OtherUser-username" className="h-full w-1/2 text-lg">
{otherUser.username}
</div>
</div>
</div>
</div>
</div>
);
};
答: 暂无答案
上一个:诺德蒙 + Socket.io
下一个:读取json文件并仅打印特定行
评论