You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Micronaut中启用跨域WebSocket连接?

解决Micronaut WebSocket跨域403错误方案

1. 修正Micronaut的CORS配置(关键)

WebSocket连接发起前会发送OPTIONS预检请求,如果你的CORS配置未覆盖WebSocket路径或允许OPTIONS方法,就会触发403,且请求可能没到达业务代码(所以日志无记录)。更新application.yml的CORS配置,确保覆盖WebSocket路径并包含必要的预检参数:

micronaut:
  server:
    cors:
      enabled: true
      configurations:
        webSocketCors:
          allowed-origins:
            - "http://dev.domain.com:8080"
          allowed-methods:
            - GET
            - POST
            - OPTIONS
            - HEAD
          allowed-headers:
            - "*"
          exposed-headers:
            - "*"
          allow-credentials: true
          allowed-patterns:
            - "/ws/**" # 匹配WebSocket路径

2. 检查Vue端WebSocket配置

确保vue-native-websocket-vue3的配置包含跨域所需参数,比如允许携带凭证(如果服务器开启了allow-credentials),并正确指定WebSocket地址:

import { createStore } from 'vuex'
import VueNativeSock from 'vue-native-websocket-vue3'

const store = createStore({
  // ...你的store配置
})

// 初始化WebSocket连接
app.use(VueNativeSock, 'ws://localhost:8081/ws', {
  store: store,
  reconnection: true,
  reconnectionAttempts: 5,
  reconnectionDelay: 3000,
  connectManually: true, // 对应你的按钮点击触发逻辑
  withCredentials: true, // 匹配服务器的allow-credentials配置
  protocols: []
})

3. 给Micronaut WebSocket端点添加跨域注解

如果上述配置仍无效,直接在WebSocket控制器类上添加@CrossOrigin注解,强制开启跨域支持:

import io.micronaut.websocket.annotation.ServerWebSocket;
import io.micronaut.http.annotation.CrossOrigin;

@CrossOrigin(origins = "http://dev.domain.com:8080", allowCredentials = "true")
@ServerWebSocket("/ws")
public class MyWebSocketServer {
  // ...你的WebSocket处理逻辑
}

4. 排查代理/防火墙拦截

如果服务器日志完全没收到请求,说明请求可能被反向代理(如Nginx)或防火墙拦截:

  • 若使用Nginx转发WebSocket请求,需添加以下配置允许WebSocket升级和跨域:
    location /ws {
      proxy_pass http://localhost:8081/ws;
      proxy_http_version 1.1;
      proxy_set_header Upgrade $http_upgrade;
      proxy_set_header Connection "upgrade";
      proxy_set_header Host $host;
      proxy_set_header Origin "http://dev.domain.com:8080";
      add_header Access-Control-Allow-Origin "http://dev.domain.com:8080";
      add_header Access-Control-Allow-Credentials "true";
    }
    
  • 检查本地防火墙或浏览器插件是否拦截了跨域WebSocket请求

内容的提问来源于stack exchange,提问作者myworkaccount

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 06:55:07