PATCH和PUT请求不适用于表单数据 [英] PATCH and PUT Request Does not Working with form-data
问题描述
我正在使用Laravel创建RESTFUL应用程序,并使用Postman测试该应用程序.当前,如果从邮递员发送的带有表单数据的数据存在PATCH
或PUT
的问题.
I am using Laravel to create a RESTFUL application and I test the application with Postman. Currently, there is an issue for PATCH
or PUT
if the data sent from Postman with form-data.
// Parameter `{testimonial}` will be sent to backend.
Route::post ('testimonials/{testimonial}', 'TestimonialController@update');
// Parameter `{testimonial}` will not be sent to backend (`$request->all()` will be empty) if sent from Postman with form-data.
Route::patch ('testimonials/{testimonial}', 'TestimonialController@update');
Route::put ('testimonials/{testimonial}', 'TestimonialController@update');
- 使用表单数据,
$request->all()
对于POST
没问题. - 使用x-www-form-urlencoded,
$request->all()
对于PATCH
,PUT
和POST
都是可以的. - 但是,如果我从邮递员发送带有表单数据的
PUT
和PATCH
,则$request->all()
将为空(参数将不会发送到后端). - Using form-data,
$request->all()
will be okay forPOST
. - Using x-www-form-urlencoded,
$request->all()
will be okay forPATCH
,PUT
, andPOST
. - However, if I am sending
PUT
andPATCH
with form-data from Postman, the$request->all()
will be empty (the parameters will not be sent to backend).
现在,解决方案是使用POST
来更新模型.我想知道为什么PATCH
和PUT
在与Postman的表单数据一起发送时不起作用.
Right now the solution is to use POST
for updating a model. I want to know why PATCH
and PUT
is not working when sent with form-data from Postman.
推荐答案
This is a known issue and the workaround suggestion as per the following Github comment is that when sending a PATCH
/ PUT
requests you should do the following:
您应该发送POST并将_method设置为PUT(与发送表单相同)以使文件可见
You should send POST and set _method to PUT (same as sending forms) to make your files visible
因此,从本质上讲,您发送的POST请求带有用于设置实际方法的参数,Laravel似乎理解这一点.
So essentially you send a POST request with a parameter which sets the actual method and Laravel seems to understand that.
根据文档:
由于HTML表单无法发出
PUT
,PATCH
或DELETE
请求,因此您需要添加一个隐藏的_method
字段来欺骗这些HTTP动词.@method
Blade指令可以为您创建此字段:
Since HTML forms can't make
PUT
,PATCH
, orDELETE
requests, you will need to add a hidden_method
field to spoof these HTTP verbs. The@method
Blade directive can create this field for you:
<form action="/foo/bar" method="POST">
@method('PUT')
...
</form>
或者,您可以使用 method_field
帮助函数来执行以上操作:
Alternatively, you can use the method_field
helper function to do the above:
method_field函数生成一个HTML隐藏的输入字段,其中包含表单的HTTP动词的欺骗值.例如,使用Blade语法:
The method_field function generates an HTML hidden input field containing the spoofed value of the form's HTTP verb. For example, using Blade syntax:
<form method="POST">
{{ method_field('PUT') }}
</form>
这篇关于PATCH和PUT请求不适用于表单数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!