我有很多关于如何在Java Spring中配置CORS的示例,但是在有websockets请求的项目中,它仍然不起作用。 它适用于mcv api路径,但是我的websockets路径的返回错误:
无法加载http://localhost:8080/chat/info?t=1537264329515:否 请求中存在“ Access-Control-Allow-Origin”标头 资源。因此,不允许原点“ http://localhost:3000” 访问。响应的HTTP状态码为403。
我的WebMvcConfig:
@Configuration
public class WebMvcConfig implements WebMvcConfigurer
{
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedOrigins("http://localhost:3000");
}
}
也许有人有相同的错误或有什么解决方案,我应该如何解决该错误?
答案 0 :(得分:1)
如果有人会有这个问题,我可以这样在WebsocketConfig中解决我的问题:
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/chat").setAllowedOrigins("http://localhost:3000").withSockJS();
}
答案 1 :(得分:0)
我不确定MVC,但是当我遇到这个问题时(虽然在ReactJs中处于开发模式),我使用了Chrome扩展程序:Allow control allow origin,它解决了这个问题。
答案 2 :(得分:0)
尝试一下,当我遇到相同的问题时,它可能对我有用,尽管可能不是最佳实践:
@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowCredentials(true)
.allowedHeaders("*")
.allowedMethods("OPTIONS", "GET", "POST", "PUT", "DELETE", "PATCH")
.allowedOrigins("*");
}
...
}
添加另一个过滤器
public class CorsFilter extends OncePerRequestFilter {
static final String ORIGIN = "Origin";
protected void doFilterInternal(
HttpServletRequest request,
HttpServletResponse response,
FilterChain filterChain) throws ServletException, IOException {
String origin = request.getHeader(ORIGIN);
response.setHeader("Access-Control-Allow-Origin", "http://localhost:4200");
response.setHeader("Access-Control-Allow-Credentials", "true");
response.setHeader("Access-Control-Allow-Methods", "PUT, POST, GET, OPTIONS, DELETE, PATCH");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "content-type, authorization");
if (request.getMethod().equals("OPTIONS"))
response.setStatus(HttpServletResponse.SC_OK);
else
filterChain.doFilter(request, response);
}
}
并添加到我的一系列过滤器中:
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
...
@Bean
public CorsFilter corsFilter() throws Exception {
return new CorsFilter();
}
答案 3 :(得分:0)
您需要尝试这个
@Configuration
@EnableWebSocketMessageBroker
@EnableScheduling
public class WebSocketConfiguration implements WebSocketMessageBrokerConfigurer {
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/stomp").setAllowedOrigins("*");
}
}