我已经在Spring Boot中实现了针对CORS的过滤器,代码如下:-
@SpringBootApplication @Component public class Application implements Filter { public static void main(String[] args) { SpringApplication.run(Application.class, args); } @Override public void init(FilterConfig filterConfig) throws ServletException { } @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) servletRequest; HttpServletResponse response = (HttpServletResponse) servletResponse; response.setHeader("Access-Control-Allow-Origin", "*"); response.setHeader("Access-Control-Allow-Credentials", "true"); response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE"); response.setHeader("Access-Control-Max-Age", "3600"); response.setHeader("Access-Control-Allow-Headers", "Content-Type, Accept, X-Requested-With, remember-me"); filterChain.doFilter(servletRequest, servletResponse); } @Override public void destroy() { } }
为了从oauth2获取access_token我已经从angularjs创建了以下对象:
{"url":"http://localhost:8080/oauth/token?grant_type=client_credentials&client_id=clientId&client_secret=clientSecret","headers":{"Authorization":"Basic token_value"},"withCredentials":true,"method":"POST"}
我在服务器上遇到以下错误:-
OPTIONS url... 401() Response for preflight has invalid HTTP status code 401
我已经在堆栈溢出中寻找类似问题的解决方案,但都没有解决我的问题。有人可以帮忙吗?
请阅读有关预检要求的更多信息。
他们只是建议浏览器(如果服务器支持跨域请求)。对此类OPTIONS请求的响应应该很好(即<400)。
OPTIONS
我认为该语句filterChain.doFilter(servletRequest,servletResponse);正在进一步传递请求,而不是返回响应。
filterChain.doFilter(servletRequest,servletResponse);