如果cors策略javaspring被阻止,如何访问后端?

1u4esq0p  于 2021-07-13  发布在  Java
关注(0)|答案(2)|浏览(400)

**结束。**此问题需要详细的调试信息。它目前不接受答案。
**想改进这个问题吗?**更新问题,使其成为堆栈溢出的主题。

28天前关门了。
改进这个问题
我使用javaspring作为后端,当前端到达我的端点时,他得到了一个错误
'访问xmlhttprequest'http://192.168.100.74:9009/v1/admin/c2da6237-22d2-433a-97b7-226d1989bd99/列出“来自源站”的用户http://localhost:3001'已被cors策略阻止:对飞行前请求的响应未通过访问控制检查:它没有http ok状态。
我使用javaspring,如何处理这个问题?谢谢

cngwdvgl

cngwdvgl1#

你需要添加一个 @CrossOrigin 对控制器方法的注解。详细说明请参见https://spring.io/guides/gs/rest-service-cors/ 在“启用cors”标题下。

watbbzwu

watbbzwu2#

您需要允许您要从中授予访问权限的客户机域调用API。为此,你可以简单地创建 CORSFilter . 下面是最小值 CORSFilter 实施:

@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class CorsFilter implements Filter {

/*
 * (non-Javadoc)
 * 
 * @see javax.servlet.Filter#init(javax.servlet.FilterConfig)
 */
@Override
public void init(FilterConfig filterConfig) throws ServletException {

}

/*
 * (non-Javadoc)
 * 
 * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest,
 * javax.servlet.ServletResponse, javax.servlet.FilterChain)
 */
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
        throws IOException, ServletException {
    HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
    HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;
    httpServletResponse.addHeader("Access-Control-Allow-Origin", "*"); // IMPORTANT: Allowed all the domains
    httpServletResponse.addHeader("Access-Control-Allow-Methods", "OPTIONS, GET, POST, DELETE, PUT, PATCH, HEAD");
    httpServletResponse.addHeader("Access-Control-Allow-Headers",
            "Origin, Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers, Access-Control-Allow-Origin, Authorization");
    httpServletResponse.addHeader("Access-Control-Expose-Headers",
            "Access-Control-Allow-Origin, Access-Control-Allow-Credentials, Content-Disposition");
    httpServletResponse.addHeader("Access-Control-Allow-Credentials", "true");
    httpServletResponse.addIntHeader("Access-Control-Max-Age", 3600);
    if ("OPTIONS".equalsIgnoreCase(httpServletRequest.getMethod())) {
        httpServletResponse.setStatus(HttpServletResponse.SC_OK);
    } else {
        filterChain.doFilter(httpServletRequest, httpServletResponse);
    }
}

/*
 * (non-Javadoc)
 * 
 * @see javax.servlet.Filter#destroy()
 */
@Override
public void destroy() {

}
}

特别关注 Access-Control-Allow-Origin 上面代码中的标题。

相关问题