我正在使用Angular开发Web应用程序 . 后端API是使用Laravel PHP框架开发的 . 我启用了CORS访问,在Laravel中创建了一个中间件 .
这是Laravel中间件
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');
}
}
我可以像这样成功地发出GET请求 .
this.http.get<IEvent[]>(this.globals.API_ENDPOINT + "event/list?email=" + email).subscribe(data=> {
//do something with the data
});
上面的GET请求工作正常 . 但问题是使用一些参数发出POST请求 .
我像这样发送POST请求 .
var formData = {
name: "My name"
}
this.http.post<ISimpleForm>(this.globals.API_ENDPOINT + "event/post", formData).subscribe(data=>{
})
如您所见,formData变量是对象 . 当我发送请求时,我在控制台中收到此错误 .
Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin
我在线尝试了很多解决方案 . 例如,使用“application-json”传递 Headers 为“Content-Type”,依此类推 . 他们都没有帮助 . 我已经在服务器端解决了CORS问题 .
但是当我将身体发送为像这样的字符串时,请求正在工作
this.http.post<ISimpleForm>(this.globals.API_ENDPOINT + "event/post", formData).subscribe(data=>{
})
当我对身体进行字符串化时,CORS错误消失了 . 但问题是当我使用$ _POST在服务器端记录请求数据时,没有任何内容传递给请求 . 所以身体是空的 .
那么,如何使用Angular中的HttpClient使用一些请求参数发出post请求?我的代码有什么问题,我该如何解决?
1 回答
我刚才得到了同样的错误 . 这个中间件适用于不适用于预检 Headers 的方法 . 检查这个Laravel 5.2 CORS, GET not working with preflight OPTIONS
建议在项目中使用github.com/barryvdh/laravel-cors而不是中间件 .