首页 文章

Ionic 2 / Angular问题用http发布到laravel api

提问于
浏览
1

我发现很难向laravel api发送http post请求 . GET方法工作正常,但我在谷歌Chrome控制台中得到以下错误

无法加载http:// localhost:8000 / api / user / auth:对预检请求的响应未通过访问控制检查:请求的资源上没有“Access-Control-Allow-Origin”标头 . 因此不允许Origin'http:// localhost:8100'访问 .

我正在寻找解决方案已经有2天了 . 我在离子官方博客上找到了一篇帖子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);
      }
    });
  }

1 回答

  • 2

    好吧,我发现我改变了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);
          }
        });
      }
    

相关问题