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.

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

报告相同问题?

悬赏问题

  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能
  • ¥15 jmeter脚本回放有的是对的有的是错的
  • ¥15 r语言蛋白组学相关问题
  • ¥15 Python时间序列如何拟合疏系数模型