Angular 2 访问控制允许标头



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

角度 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;
}

弹簧过滤器 :

 @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。预检响应中的访问控制允许标头不允许请求标头字段正文。

对于 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

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"]
})); 

相关内容

  • 没有找到相关文章

最新更新