我尝试覆盖Grails的spring websocket plugin的默认配置,如下所示:
@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”标头。我总是得到“XMLHttpRequest无法加载http://localhost:8080/app/stomp/info。请求的资源上没有'Access-Control-Allow-Origin'标题。因此不允许原点”http://localhost“访问。”
答案 0 :(得分:2)
我使用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)
}
希望这有助于某人。
答案 1 :(得分:1)
我将grails-3.0.2 / grails-spring-websocket-2.0.0示例应用程序推送到https://github.com/zyro23/so-30891198,这表明它应该正常工作。
curl -H "Origin: http://localhost:8080" --verbose http://localhost:8080/stomp/info
HTTP/1.1 200 OK
Access-Control-Allow-Origin: http://localhost:8080
curl -H "Origin: http://localhost" --verbose http://localhost:8080/stomp/info
HTTP/1.1 200 OK
Access-Control-Allow-Origin: http://localhost
和使用grails-2.5.0 / spring-websocket-1.3.0的第二个样本:https://github.com/zyro23/so-30891198-2
curl -H "Origin: http://localhost:8080" --verbose http://localhost:8080/so-30891198-2/stomp/info
HTTP/1.1 200 OK
Access-Control-Allow-Origin: http://localhost:8080
curl -H "Origin: http://localhost" --verbose http://localhost:8080/so-30891198-2/stomp/info
HTTP/1.1 200 OK
Access-Control-Allow-Origin: http://localhost