【问题标题】:get request working on api but post is giving error获取在 api 上工作的请求,但 post 给出错误
【发布时间】:2017-09-20 06:41:50
【问题描述】:

我正在尝试以角度调用 Laravel API:

search(data){

 console.log(data);

 this.http.get('http://localhost:8000/flight',JSON.stringify(data))
    .subscribe(res=>{
        console.log(res);
  });

}

以上是使用 GET 请求。

 search(data){
   console.log(data);
   this.http.post('http://localhost:8000/flight',JSON.stringify(data))
        .subscribe(res=>{
           console.log(res);
  });
}

但不适用于 POST 请求

这是我得到的错误:

请求中没有“Access-Control-Allow-Origin”标头 资源。因此不允许使用原点“http://localhost:4200” 访问。

即使我的 cors middelware 编写正确

 return $next($request)->header('Access-Control-Allow-Origin', '*')
        ->header('Access-Control-Allow-Credentials', true )
        ->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS')
        ->header('Access-Control-Allow-Headers',' Origin, Content-Type, X-Auth-Token');

【问题讨论】:

  • 这是服务器上的 CORS 问题
  • 你能解释一下我是 laravel 和 angular 的新手吗
  • 不,先生,我不知道您需要在 lavel api github.com/barryvdh/laravel-cors987654322@ 中启用 CORS
  • 但我已经通过编写 cors 中间件启用了它,并且我还在我的 RouteServiceProvider 中添加了它
  • 了解您是否真的编写正确的唯一方法是查看开发人员工具中的网络选项卡,看看您的本地服务器是否确实返回了 CORS 标头。

标签: angular laravel


【解决方案1】:

在你的 post 方法中尝试这样:

在 laravel 服务器端:

Header set Access-Control-Allow-Origin "http://localhost:3000"

(or)

header("Access-Control-Allow-Origin: *");
    header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Authorization, If-Modified-Since, Cache-Control, Pragma");

需要重启apache。

角度中的post方法

search(data: any) {
    return this.http.post('http://localhost:8000/flight', data).map(res => {
        const jsonResponse = res.json();
        return jsonResponse;
    });
}

【讨论】:

    【解决方案2】:

    我只需要更改代码,即(删除 JSON.stringify),因为它发送的是字符串而不是 json 对象

     search(data){
     console.log(data);
      this.http.post('http://localhost:8000/flight',data)
        .subscribe(res=>{
           console.log(res);
      });
     }
    

    【讨论】:

      猜你喜欢
      • 2019-01-01
      • 1970-01-01
      • 2018-03-18
      • 1970-01-01
      • 2015-06-18
      • 2017-01-22
      • 2019-11-04
      • 1970-01-01
      • 2020-05-26
      相关资源
      最近更新 更多