如何在 Micronaut 中启用跨域 Websocket 连接?"/>
如何在 Micronaut 中启用跨域 Websocket 连接?
我正在尝试实现一个新的 Micronaut 微服务,它将成为一个 Websocket 服务器,假设它在
http://localhost:8081
上运行,并且 Websocket 位于 ws://localhost:8081/ws
上。
客户端将是在不同域上本地运行的 Vue.js UI,比如
:8080
。
当我单击将触发 websocket 连接和数据传输的 UI 按钮时,我在 Chrome 中得到以下信息:
Common.umd.js:8 WebSocket connection to 'ws://localhost:8081/ws' failed:
以及 Firefox 中的以下内容:
GET ws://localhost:8081/ws [HTTP/1.1 403 Forbidden 412ms]
Firefox can’t establish a connection to the server at ws://localhost:8081/ws. Common.umd.js:formatted:3191:34
在 Firefox 中,它会给出
403
错误,但在 Chrome 中的网络选项卡下,它只是说对 ws://localhost:8081/ws
的请求有 Finished
,没有状态代码。我不太确定这是怎么回事,但 403
一定来自 Micronaut 服务器,对吗?
Micronaut websocket 服务器代码通常看起来像这样(我省略了详细信息,因为 Micronaut 服务器访问日志中没有提到任何有关
403
的内容,这意味着甚至没有到达代码):
@ServerWebSocket("/ws")
public class Server {
/** Class logger. */
private static final Logger log = LoggerFactory.getLogger(Server.class);
/** Micronaut application context. */
@Inject ApplicationContext ctx;
/** Service configuration. */
@Inject Configuration configuration;
/** WebSocket broadcaster. */
@Inject WebSocketBroadcaster broadcaster;
/** The RabbitMQ message producer. */
@Inject ApiProducer producer;
/**
* Handler for connection open event.
*
* @param session - the created WS session.
* @return Publisher for the startup confirmation message.
*/
@SuppressWarnings("static-method")
@OnOpen
public Publisher<String> onOpen(WebSocketSession session) {
...
}
/**
* Handler for message received event.
*
* @param message - the command payload
* @param session - current WS session
* @return Publisher for the response message.
*/
@SuppressWarnings("unchecked")
@OnMessage
public Publisher<String> onMessage(String message, WebSocketSession session) {
...
}
public Mono<String> onNotification(String notification, UUID correlationId) {
...
}
/**
* Handler for connection close event.
*
* @param session - the WS session to be closed.
*/
@SuppressWarnings("static-method")
@OnClose
public void onClose(WebSocketSession session) {
...
}
}
在 Vue.js 方面,我们将
vuex
createStore
方法与 VueNativeSock
包中的 vue-native-websocket-vue3
模块结合使用。
同样在 Micronaut 方面,我尝试使用
application.yml
文件中的以下内容启用 CORS 请求的处理:
micronaut:
application:
name: application-name
server:
cors:
enabled: true
port: 8081
但是,这还是不行。
一些额外的上下文:当我使用
http://localhost:8080
作为 UI 域并保留其他所有内容相同时,它可以毫无问题地连接并发送数据。仅当 UI 具有不同的域时才会出现问题,生产中也会出现这种情况。
如有任何帮助,我们将不胜感激。
回答如下:所以我最终在这里找到了答案:https://github/micronaut-projects/micronaut-core/issues/8560在sdelamo 1月11日的第一个评论中。
我需要使用:
micronaut:
application:
name: application-name
server:
cors:
enabled: true
configurations:
ui:
allowed-origins: "http://dev.domain:8080"
port: 8081
这与我阅读的文档相矛盾,该文档说配置属性用于限制不允许访问特定域。
更多推荐
如何在 Micronaut 中启用跨域 Websocket 连接?
发布评论