【发布时间】:2020-11-18 13:45:11
【问题描述】:
我正在创建一个以节点为后端的反应应用程序但显示此错误
从源“http://localhost:3000”访问“http://localhost:5000/socket.io/?id=21af3bd7-faea-4300-8e2a-6866fe8274b1&EIO=4&transport=polling&t=NNPqjV0”处的 XMLHttpRequest已被 CORS 政策阻止:请求的资源上不存在“Access-Control-Allow-Origin”标头。
这是我的完整服务器端代码
const cors = require("cors");
const express = require("express");
const app = express();
app.use(
cors({
origin: "http://localhost:3000",
})
);
io.on("connection", (socket) => {
const id = socket.handshake.query.id;
socket.join(id);
socket.on("send-message", ({ recipients, text }) => {
recipients.forEach((recipient) => {
const newRecipients = recipients.filter((r) => r !== recipient);
newRecipients.push(id);
socket.broadcast.to(recipient).emit("receive-message", {
recipients: newRecipients,
sender: id,
text,
});
});
});
});
【问题讨论】:
-
使用 app.use(cors());所以它会让访问来自不同服务器的api,你不需要给出特定的地址