我使用Laravel 5.2作为API,使用AngularJS作为客户端。 PUT
的角度默认请求标题如下所示:
PUT /v1/contact/1
Content-Type: application/json; charset=UTF-8
Authorization: Bearer token
由于所有这3个标头都不是默认标头,因此浏览器会在每次操作之前发送选项请求,以确保接受这些标头。 我想避免这个选项请求,因为性能。
为了实现这一点,我在/v1/contact/1?token=token
我使用的另一个技巧是,我在application/json
和Laravel端发送给Laravel text/plain
而不是Content-Type
,而是覆盖中间件中的标头:
if ( $request->header('Content-Type') == 'text/plain' ) {
$request->headers->set('Content-Type', 'application/json');
}
最后一个问题是,为了发出PUT
请求,我发出POST
请求,因为Laravel接受_method
,我在所有表单中输入了一个输入:
<input type="hidden" name="_method" value="PUT">
此字段已被识别,并被视为真实的PUT
请求。
文档:https://laravel.com/docs/5.1/routing#form-method-spoofing
唯一的问题是,当我发出这样的请求时,因为Laravel在中间件之前检查请求中的_method
参数而Content-Type
是text/plain
,所以它不会这样做。 t将帖子数据识别为对象。
我尝试了相同的操作,只将Content-Type
更改为application/json
,并且没有任何问题。