Socket.io - 套接字服务器不控制任何内容 - 已被 CORS 策略阻止:Access-Control-Allow-Origin header 包含无效值

Socket.io - Socket server doesn't console anything- has been blocked by CORS policy: The Access-Control-Allow-Origin header contains the invalid value

我正在建立一个论坛站点,两个用户在连接后可以 post 状态然后对他们发表评论。对于评论,我使用 socket.io .

但是,每当我成功连接(登录)到我的论坛时,我注意到套接字服务器没有任何控制台。同时我在控制台中期待这条消息 A new user is connected ! .

我不确定我的代码是否做错了,所以它们是:


我在我的套接字服务器中安装了 expressnodemonsocket.io :

package.json

{
"name": "socket",
"version": "1.0.0",
"description": "",
"main": "app.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
  "express": "^4.17.3",
  "nodemon": "^2.0.15",
  "socket.io": "^4.4.1"
  }
}

app.js

const io = require("socket.io")(4000, {
cors: {
    origin: "http//localhost:3000",
},
});


io.on('connection', (socket) => {
  console.log('A new user is connected !');
})
io.on('disconnect', () => {
  console.log('User has left !');
});

我还安装了 socket.io-client 在客户端(前面),然后在我的网页中,我添加了这段代码:

import { io } from 'socket.io-client'
export default () => {

  //implement socket
  const socket = useRef()

  useEffect(() => {
      socket.current = io("ws://localhost:4000")
  }, [])

return (
  //some html code
)
}

F12 控制台每 ~4 秒显示一次这些错误:

    Failed to load resource: net::ERR_FAILED

    Access to XMLHttpRequest at 'http://localhost:4000/socket.io/? 
    EIO=4&transport=polling&t=O09cPlb' from origin 'http://localhost:3000' has been blocked by 
    CORS policy: The 'Access-Control-Allow-Origin' header contains the invalid value 
    'http//localhost:3000'.

每 ~4 秒以红色显示相同的状态:CORS 错误



Visual studio 代码的控制台总是显示此 我刷新浏览器或 ctrl+S(保存)代码的次数:

[nodemon] starting 'node apde app.js'

我尝试从 Console dev 中的应用程序中删除 cookie,清除缓存,注销并重新登录,但 none 解决了我的问题。

在你的app.js

cors: {
    origin: "http//localhost:3000",
}

应该是

cors: {
    origin: "http://localhost:3000",
}

使用
将 cors 插件安装到您的 node.js 后端 npm i cors

在您的节点 main.js 文件中要求它并按如下方式实现它:

let express = require('express');
let cors = require('cors');
let app = express();
app.use(cors());

如果您不想安装插件,请将以下代码添加到节点后端的 main.js 文件中。

let express = require('express');
let app = express();
app.all('/*', function(req, res, next) {
   res.header("Access-Control-Allow-Origin", "*");
   res.header("Access-Control-Allow-Headers", "X-Requested-With");
   next();
});