从源访问 XMLHttpRequest 已被 CORS 策略阻止 请求的资源上不存在“Access-Control-Allow-Origin”标头

问题描述 投票:0回答:1

客户端连接到服务器时出现问题。

通过 Live Server,端口 3000 上的服务器和端口 5001 上的应用程序:

从源“http://127.0.0.1:5001”访问“http://localhost:3000/socket.io/?EIO=4&transport=polling&t=Oz_5Qur”处的 XMLHttpRequest 已被 CORS 策略阻止:无“访问” -Control-Allow-Origin'标头存在于请求的资源上。

错误消息大约每秒重复一次。

我尝试过查看许多类似的帖子,但无济于事。
预期结果:建立新连接时显示“用户已连接”终端日志,以及用户断开连接时显示日志。

index.js(服务器)

import express from 'express';
import { createServer } from 'node:http';
import { fileURLToPath } from 'node:url';
import { dirname, join } from 'node:path';
import { Server } from 'socket.io';
import cors from 'cors';

const app = express();
const server = createServer(app);
const io = new Server(server);
const __dirname = dirname(fileURLToPath(import.meta.url));

app.use(cors()); 
app.use('/socket.io', express.static(join(__dirname, 'node_modules', 'socket.io', 'client-dist')));
app.use(express.static(join(__dirname, 'myapp')));
console.log(__dirname);

app.use((req, res, next) => {
  res.setHeader("Access-Control-Allow-Origin", "http://127.0.0.1:5001/");
  res.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, DELETE");
  res.setHeader("Access-Control-Allow-Headers", "Origin, Accept, Content-Type, Authorization");
  next();
})
app.get('/', (req, res) => {
  res.sendFile(join(__dirname, 'server.html'));
});

io.on('connection', (socket) => {
  console.log('a user connected');

  socket.on('disconnect', () => {
    console.log('user disconnected');
  });
});

server.listen(3000, () => {
  console.log('server running at http://localhost:3000');
});

client.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="styles.css">
</head>
<body>
    <script src="http://localhost:3000/socket.io/socket.io.js"></script>
    <script>
        var socket = io('http://localhost:3000');
    </script>
</body>
</html>

server.html(没有问题)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="styles.css">
</head>
<body>
    <script src="/socket.io/socket.io.js"></script>
    <script>
      var socket = io();
    </script>
</body>
</html>
javascript node.js sockets socket.io cors
1个回答
0
投票

您需要为您的套接字服务器定义 cors,如下所示,在您的 index.js(服务器)文件中。

如果您只想允许 http://localhost:3000,您还可以使用 origin: ['http://localhost:3000] 代替 origin: '*'

const io = new Server(server, {
    cors: {
      origin: '*',
      methods: ['GET', 'POST'],
      transports: ['websocket', 'polling'],
      credentials: true,
    }
  });
© www.soinside.com 2019 - 2024. All rights reserved.