angular - Ionic 2/Angular 与 http post 到 laravel api 的问题

标签 angular laravel http ionic2 cors

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

Failed to load http://localhost:8000/api/user/auth: 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:8100' is therefore not allowed access.

自从我寻找解决方案以来已经过去了两天。 我在这里找到了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);
      }
    });
  }

最佳答案

好吧,我找到了解决方案 我已经更改了 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);
      }
    });
  }

关于angular - Ionic 2/Angular 与 http post 到 laravel api 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48848766/

相关文章:

css - Angulr2 : custom css conflict with third-party css

angular - TS2416 : Property 'canActivate' in type 'MyGuard' is not assignable to the same property in base type 'CanActivate'

angular - ionic 4, ionic 滑动垂直滚动不起作用

Laravel 集合 : Flatten with full key name

http - 搜索引擎是否尊重 HTTP header 字段 “Content-Location” ?

php - 在没有API的情况下如何测试客户端?

javascript - 为不起作用的动态字段创建添加按钮

Laravel 验证日期范围数组

php - Laravel 获取具有关系枢轴条件的模型

c# - 跳过 X 帧