gpt4 book ai didi

grails - 如何在 Grails websocket 插件中启用跨域请求

转载 作者:行者123 更新时间:2023-12-02 13:55:43 24 4
gpt4 key购买 nike

我试图覆盖 spring websocket plugin 的默认配置对于 Grails,像这样:

@Configuration
@EnableWebSocketMessageBroker
class CorsWebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {

@Override
void configureMessageBroker(MessageBrokerRegistry messageBrokerRegistry) {
messageBrokerRegistry.enableSimpleBroker "/queue", "/topic"
messageBrokerRegistry.setApplicationDestinationPrefixes "/app"
}

@Override
void registerStompEndpoints(StompEndpointRegistry stompEndpointRegistry) {
StompWebSocketEndpointRegistration registration = stompEndpointRegistry.addEndpoint("/stomp")
registration.setAllowedOrigins('http://localhost', 'http://localhost:8080')
registration.withSockJS().setSupressCors(false)
}

// [...]
}

我也尝试过执行 .setAllowedOrigins('*'),但它仍然无法正常工作。

但是,当我注册我的客户端时,永远不会在/stomp/info 端点上设置“Access-Control-Allow-Origin” header 。我总是得到“XMLHttpRequest 无法加载 http://localhost:8080/app/stomp/info。请求的资源上不存在 'Access-Control-Allow-Origin' header 。因此不允许访问 Origin ' http://localhost'。”

最佳答案

我使用来自 https://github.com/davidtinker/grails-cors 的信息解决了这个问题.
Grails-cors 插件不适用于 grails 3.x,但在 repo 自述文件中有一些信息。我将在此处复制/粘贴:

此插件不适用于 Grails 3。要在 Grails 3 项目中处理 CORS,您可以在 src/main/java 下的某处创建一个 servlet 过滤器。 :

@Priority(Integer.MIN_VALUE)
public class CorsFilter extends OncePerRequestFilter {

public CorsFilter() { }

@Override
protected void doFilterInternal(HttpServletRequest req, HttpServletResponse resp, FilterChain chain)
throws ServletException, IOException {

String origin = req.getHeader("Origin");

boolean options = "OPTIONS".equals(req.getMethod());
if (options) {
if (origin == null) return;
resp.addHeader("Access-Control-Allow-Headers", "origin, authorization, accept, content-type, x-requested-with");
resp.addHeader("Access-Control-Allow-Methods", "GET, HEAD, POST, PUT, DELETE, TRACE, OPTIONS");
resp.addHeader("Access-Control-Max-Age", "3600");
}

resp.addHeader("Access-Control-Allow-Origin", origin == null ? "*" : origin);
resp.addHeader("Access-Control-Allow-Credentials", "true");

if (!options) chain.doFilter(req, resp);
}
}

引用 grails-app/conf/spring/resources.groovy 中的过滤器:
beans = {
corsFilter(CorsFilter)
}

希望这可以帮助某人。

关于grails - 如何在 Grails websocket 插件中启用跨域请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30891198/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com