【问题标题】:Ionic 2 / Angular issue with http post to laravel apiIonic 2 / Angular 问题与 http post 到 laravel api
【发布时间】:2018-07-28 15:51:54
【问题描述】:

我发现很难将 http post 请求发送到 laravel api。 GET 方法工作正常,但在 google chrome 控制台中出现以下错误

无法加载http://localhost:8000/api/user/auth:响应 预检请求未通过访问控制检查:否 请求中存在“Access-Control-Allow-Origin”标头 资源。因此不允许使用原点“http://localhost:8100” 访问。

我已经 2 天了,因为我正在寻找解决方案。 我在 ionic 官方博客上找到了一个帖子 https://blog.ionicframework.com/handling-cors-issues-in-ionic/ 但它似乎没有帮助。

谢谢

这是我的代码

authUser(email, pass) {       
    const httpOptions = {
      headers: new HttpHeaders({
        'Content-Type': 'application/json'
      })
    };
    let data = JSON.stringify(
      {
        "email": email,
        "password": pass
      }
    );
    this.http.post(this.API_URL+'user/auth', data, httpOptions).subscribe(data => {
      if(data['success']) {
        this.user = data['response'];
      } else {
        this.hasError = data['message'];
        console.log(this.hasError);
      }
    });
  }

【问题讨论】:

  • 在您的 API 服务器上启用 CORS github.com/barryvdh/laravel-cors
  • 感谢@TiepPhan,但我已经在 laravel 中设置了 cors 中间件,并且我的 GET 请求工作正常
  • 根据您上面的错误消息,您的服务器没有正确设置为接受 Origin localhost:8100。请验证您的服务器以接受上述来源。
  • 感谢@TiepPhan 的帮助,我也会尝试您的解决方案。

标签: angular laravel http ionic2 cors


【解决方案1】:

我找到了解决方案 我已经更改了 Content-Type: application/json 和数据体,下面是示例

authUser(email, pass) {       
    const httpOptions = {
      headers: new HttpHeaders({
        'Content-Type': 'application/x-www-form-urlencoded' //updated
      })
    };
    let data = "email="+email+"&password="+pass+""; //updated

    this.http.post(this.API_URL+'user/auth', data, httpOptions).subscribe(data => {
      if(data['success']) {
        this.user = data['response'];
        console.log(this.user);
      } else {
        this.hasError = data['message'];
        console.log(this.hasError);
      }
    });
  }

【讨论】:

  • 你拯救了我的一天。谢谢。当我在谷歌上搜索如何通过 ionic3 在 laravel 中调用 post 方法时,我什么也没找到。我的内容类型 json 和 cors 错误杀死了我。但你幸免于难,谢谢
  • 如果我使用不记名令牌并想为此添加授权然后出现 CORS 错误,该怎么办
  • @KhanSahrukh 是的,当然这里是stackoverflow.com/q/56157129/308578
猜你喜欢
  • 2017-12-07
  • 2015-11-28
  • 2018-07-18
  • 2020-11-11
  • 2018-08-05
  • 1970-01-01
  • 2016-10-16
  • 2017-03-29
  • 1970-01-01
相关资源
最近更新 更多