doujingke4981 2018-04-09 10:49
浏览 353
已采纳

由于CORS问题,无法在Angular中发出HttpClient post请求

I am developing a Web application using Angular. Backend API is developed using Laravel PHP framework. I enabled the CORS access creating a middleware in the Laravel.

This is the Laravel middleware

class Cors
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        return $next($request)
        ->header('Access-Control-Allow-Headers','X-Requested-With,content-type')
        ->header('Access-Control-Allow-Origin', '*')
        ->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
    }
}

I can successfully make the GET request like this.

this.http.get<IEvent[]>(this.globals.API_ENDPOINT + "event/list?email=" + email).subscribe(data=> {
    //do something with the data
});

The above GET request is working fine. But the problem is with making POST request with some parameters.

I send the POST request like this.

var formData = {
   name: "My name"
}
this.http.post<ISimpleForm>(this.globals.API_ENDPOINT + "event/post", formData).subscribe(data=>{

})

As you can see the formData variable is object. When I send the request, I got this error in console.

Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 

I tried lots of solution online. For example, passing headers with "Content-Type" with "application/json" and so on. None of them helped. I already solved CORS issue in the server side as well.

But the request is working when I send the body it as string like this

this.http.post<ISimpleForm>(this.globals.API_ENDPOINT + "event/post", formData).subscribe(data=>{

    })

The CORS error is gone when I stringify the body. But the problem is when I log the request data in the server side using $_POST, nothing is passed to the request. So the body is empty.

So, how can I make post request with some request parameters using HttpClient in Angular? What is wrong with my code and how can I fix it?

  • 写回答

1条回答 默认 最新

  • drtwqc3744 2018-04-09 11:48
    关注

    I got the same error a while ago. this middleware works for methods not for preflight header. Check this Laravel 5.2 CORS, GET not working with preflight OPTIONS

    Suggesting this to use in your project github.com/barryvdh/laravel-cors instead of middleware.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 jupyterthemes 设置完毕后没有效果
  • ¥15 matlab图像高斯低通滤波
  • ¥15 针对曲面部件的制孔路径规划,大家有什么思路吗
  • ¥15 钢筋实图交点识别,机器视觉代码
  • ¥15 如何在Linux系统中,但是在window系统上idea里面可以正常运行?(相关搜索:jar包)
  • ¥50 400g qsfp 光模块iphy方案
  • ¥15 两块ADC0804用proteus仿真时,出现异常
  • ¥15 关于风控系统,如何去选择
  • ¥15 这款软件是什么?需要能满足我的需求
  • ¥15 SpringSecurityOauth2登陆前后request不一致