Nginx 服务器块和 socket.io - CORS

Nginx 服务器块和 socket.io - CORS

我已经使用此服务器块结构运行应用程序一段时间了,它从来没有给我带来任何问题。

geo $authentication {
  default "Authentication required";
  `Some ip number` "off";
}

server {
  listen         80 default_server;
  listen    [::]:80 default_server;
  server_name my.domain.com;
  return 301 https://$host$request_uri;
}

server {
  listen 443 ssl http2;
  listen [::]:443 ssl http2;
  ssl_certificate /etc/letsencrypt/live/my.domain.com/fullchain.pem; # managed by Certbot
  ssl_certificate_key /etc/letsencrypt/live/my.domain.com/privkey.pem; # managed by Certbot

  include /etc/letsencrypt/options-ssl-nginx.conf;
  ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem;

  server_name my.domain.com;
  client_max_body_size 200M;
  
  root /var/www/;
  index index.php index.html index.htm;

  location / {
    add_header Access-Control-Allow-Origin *;
    auth_basic $authentication;
    auth_basic_user_file /var/www/.htpasswd;
    try_files $uri $uri/ =404;
  }

  # Here is for example the app where I am running socket.io from
  location /myapp {
    auth_basic $authentication;
    auth_basic_user_file /var/www/.htpasswd;
    try_files $uri $uri/ =404;
  }

  # If this app has some sort of api route for express I do a proxy pass
  location /api/upload/ {
    proxy_pass http://localhost:5003/api/upload;
  }

但是,我正在尝试使用 socket.io,我无法理解子文件夹是否存在问题,因为如果我尝试从客户端连接,我会不断收到 CORS,如下所示

import { io } from 'socket.io-client'
const socket = io('http://localhost:5003')

在服务器上我得到了这个

import express from 'express'
import { createServer } from 'http'
import { Server } from 'socket.io'

const app = express()
const prod = process.env.NODE_ENV === 'production'
const port = process.env.PORT || prod ? 5003 : 4000
const httpServer = createServer(app)

const io = new Server(httpServer, {
  cors: {
    origin: '*',
    methods: ['GET', 'POST']
  }
})

const connections = []

io.on('connection', (socket) => {
  connections.push(socket)
  console.log(`Socket id ${socket.id} connected`)

  socket.on('disconnect', () => {
    connections.splice(connections.indexOf(socket), 1)
  })
})

httpServer.listen(port, () => console.log(`App listening on port ${port}.`))

我可以看到,在开发过程中一切运行正常,并且建立了 Web 套接字连接:

在此处输入图片描述

在 CORS 之后的服务器上当然不会:

在此处输入图片描述

无论我怎么尝试,我最终总是得到这样的结果: 在此处输入图片描述

答案1

在您的第二张图片中,socket.io 库正在使用轮询。这可能是因为您没有正确设置 nginx 配置。

location /socket.io/ {
    proxy_pass http://localhost:5003/socket.io/;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "Upgrade";
    proxy_set_header Host $host;
}

这里是一个很好的例子。改变之后你应该能够使用下面的命令来访问你的后端:

import { io } from 'socket.io-client'
const socket = io()

请注意,如果您的所有请求都通过 Nginx,则您不需要 CORS 指令,因为所有请求都将发送到相同的地址和端口。

相关内容