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

查看:94
本文介绍了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);
    });
  }

获取方法"有效,但邮政"无效.他们都在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",内容类型,如果不匹配");
  • 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天全站免登陆