如何为CORS指定响应头? [英] How to specify response headers to CORS?

查看:708
本文介绍了如何为CORS指定响应头?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在春季构建了一个后端REST API,我的朋友正在构建一个Angular JS前端应用程序来调用我的API.我有一个带有键Authorization的令牌头和一个可以访问服务的值,否则它会拒绝我可以从Postman和REST客户端接收API,但是经过测试,他说他在飞行前得到401 Unauthorized Error.下面是我的doFilterInternal方法.

I am building a backend REST API in spring and my friend is building a Angular JS front end app to call my API.I have a token header with key Authorization and a value which gives access to the service otherwise it refuses.From Postman and REST client I am able to receive the API but when tested he says he gets 401 Unauthorized Error on preflight.Below is my doFilterInternal method.

protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
        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, Authorization");
}

但是当他用Angular JS中的令牌调用API时,会得到

But when he calls the API with the token in Angular JS he gets

所以我在此处并添加了属性

spring.mvc.dispatch-options-request=true

在application.properties中.但是,错误似乎仍然是

in the application.properties.But stillt he error seems to be like

预检响应中包含无效的https状态码401

感谢您的帮助.

推荐答案

这里是避免预检错误的过滤器

Here is the filter which avoid the preflight error

        @Override
        protected void doFilterInternal(HttpServletRequest req, HttpServletResponse res, FilterChain chain) throws ServletException, IOException {
            LOG.info("Adding CORS Headers ........................");        
            res.setHeader("Access-Control-Allow-Origin", "*");
            res.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
            res.setHeader("Access-Control-Max-Age", "3600");
            res.setHeader("Access-Control-Allow-Headers", "X-PINGOTHER,Content-Type,X-Requested-With,accept,Origin,Access-Control-Request-Method,Access-Control-Request-Headers,Authorization");
            res.addHeader("Access-Control-Expose-Headers", "xsrf-token");
            if ("OPTIONS".equals(req.getMethod())) {
             res.setStatus(HttpServletResponse.SC_OK);
            } else { 
             chain.doFilter(req, res);
            }        
        }

在帖子 查看全文

登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆