Angular 2访问控制允许标头

时间:2017-04-05 13:47:32

标签: angular spring-boot cross-domain

我尝试使用Angular 2连接到Spring rest登录方法

Angular 2请求:

    let body = JSON.stringify({ "email":"email", "password":"password" });
    this.http.post('http://localhost:9999/login/authent', body, {headers:this.getHeaders()})
  .subscribe(
    response => {
    debugger;
      localStorage.setItem('id_token', response.json().id_token);
      this.router.navigate(['home']);
    },
    error => {
      alert(error.text());
      console.log(error.text());
    }
  );


 getHeaders() {
   // let username = this.variables.getUsername();
   // let password = this.variables.getPassword();
    let username = "username";
    let password = "password";
    let headers =  new Headers();
    //headers.append("Content-Type", "text/xml");
    headers.append("Access-Control-Allow-Origin", "*");
    headers.append("Access-Control-Allow-Credentials", "true"); 
    headers.append("Authorization", "Basic " + btoa(username + ":" + password));
    headers.append("Access-Control-Allow-Methods", "GET, HEAD, OPTIONS, POST, PUT, DELETE");
    headers.append("Content-Type", "application/json,application/x-www-form-urlencoded");
    headers.append("Access-Control-Request-Headers", "Content-type,X-Requested-With,Origin,accept");
    let options = new RequestOptions({headers: headers});
    console.log(JSON.stringify(options));
    return options;
}

Spring过滤器:

 @Component
 public class WebConfig  implements Filter {

     public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
            HttpServletResponse response = (HttpServletResponse) res;
            response.setHeader("Access-Control-Allow-Origin", "*");
            response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
            response.setHeader("Access-Control-Max-Age", "3600");
            response.setHeader("Access-Control-Allow-Credentials", "true");
            response.setHeader("Access-Control-Allow-Headers", "application/json,application/x-www-form-urlencoded");
            chain.doFilter(req, res);
        }

        public void init(FilterConfig filterConfig) {}

        public void destroy() {}

请求响应为200,我有控制台错误:

XMLHttpRequest无法加载http://localhost:9999/login/authent。预检响应中的Access-Control-Allow-Headers不允许使用请求标头字段正文。

2 个答案:

答案 0 :(得分:1)

对于CORS标头,最好使用Spring自己的CORS支持,而不是自定义过滤器。检查这个方法: https://spring.io/guides/gs/rest-service-cors/

我猜你的后端没有正确响应OPTIONS预检请求 - 可能会返回HTTP 404,因为你没有端点(你的控制器只处理POST请求)。

有关CORS的更多信息,您可以查看Mozilla: https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS

答案 1 :(得分:0)

Access-Control-Allow-Origin is a **response header**, not a **request header**
you need to fix the permission in your backend. so You must create cors.js file that contains all necessary permissions.

    function crosPermission(){
      this.permission=function(req,res,next){
        res.header('Access-Control-Allow-Origin','*');
        res.header('Access-Control-Allow-Headers','Content-Type');
        res.header('Access-Control-Allow-Methods','GET','POST','PUT','DELETE','OPTIONS');
        next();
      }
    }

    module.exports= new crosPermission();

**next step**
You need to add some line in your app.js
var cors=require('./cors');
app.use(cors.permission)

**for allow-Headers you can use also**
app.use(cors({
    allowedHeaders: ["Content-Type", "Authorization"]
}));