Angular 5:预检响应具有无效的 HTTP 状态代码 403 [英] Angular 5: Response for preflight has invalid HTTP status code 403

查看:45
本文介绍了Angular 5:预检响应具有无效的 HTTP 状态代码 403的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我向服务器发送 POST 请求时,出现错误:

When I send a POST request to the server I get an error:

Failed to load http://localhost:8181/test: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access. The response had HTTP status code 403.

后端是用 Java Spring 编写的.我创建测试的方法:

The backend is written in Java Spring. My method for creating a test:

createTest() {
    const body = JSON.stringify({
      'description': 'grtogjoritjhio',
      'passingTime': 30,
      'title': 'hoijyhoit'
    });

    const httpOptions = {
      headers: new HttpHeaders({
          'Content-Type': 'application/json',
          'Accept': 'application/json'
        }
      )
    };

    return this._http.post(`${this._config.API_URLS.test}`, body, httpOptions)
      .subscribe(res => {
        console.log(res );
      }, error => {
        console.log(error);
    });
  }

Get 方法有效,但 Post 无效.他们都在 Swagger 和 Postman 工作.我多次更改 POST 方法.我的代码中的标头不起作用,但我解决了将它们扩展到 Google Chrome 的问题.只有一个错误:

Get Method works, but Post doesn't. They both work in Swagger and Postman. I changed POST method many times. The headers in my code do not work, but I solved the problem with them expanding to Google Chrome. There was only an error:

Response for preflight has invalid HTTP status code 403.

在我看来,这不是 Angular 的问题.请告诉我我或我的朋友(编写后端)如何解决这个问题.

It seems to me that this is not Angular problem. Please tell me how I or my friend (who wrote the backend) can solve this problem.

推荐答案

问题:

对于任何跨域 POST 请求,浏览器将首先尝试执行 OPTIONS 调用,并且当且仅当该调用成功时,它才会执行真正的 POST 调用.但在您的情况下, OPTIONS 调用失败,因为没有 'Access-Control-Allow-Origin' 响应标头.因此,实际调用将不会完成.

For any Cross-Origin POST request, the browser will first try to do a OPTIONS call and if and only if that call is successful, it will do the real POST call. But in your case, the OPTIONS call fails because there is no 'Access-Control-Allow-Origin' response header. And hence the actual call will not be done.

SLOUTION :

为此,您需要在服务器端添加 CORS 配置以设置跨源请求所需的适当标头,例如:

So for this to work you need to add CORS Configuration on the server side to set the appropriate headers needed for the Cross-Origin request like :

  • response.setHeader("Access-Control-Allow-Credentials", "true");
  • response.setHeader("Access-Control-Allow-Headers", "content-type, if-none-match");
  • response.setHeader("Access-Control-Allow-Methods", "POST,GET,OPTIONS");
  • response.setHeader("Access-Control-Allow-Origin", "*");
  • response.setHeader("Access-Control-Max-Age", "3600");

这篇关于Angular 5:预检响应具有无效的 HTTP 状态代码 403的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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