【发布时间】:2021-06-10 06:58:53
【问题描述】:
上下文
我在 Laravel 8 中使用 PUT 请求实现用户信息更新。我使用 Postman 发送请求并查看结果。
预期行为
我的PUT 请求到达控制器的功能,该功能被授权更新经过身份验证的用户。后者更新成功。于是validate调用成功执行,并找到了请求中的数据。
实际行为
我的PUT 请求到达控制器的功能,该功能被授权更新经过身份验证的用户。后者没有成功更新。事实上,validate 调用执行成功,但没有找到请求中的数据。
相反,数据验证说:
{ "message": "给定的数据无效。", “错误”:{ “电子邮件”: [ “电子邮件字段是必需的。” ], “姓名”: [ “该名称字段是必需的。” ] } }
路线和请求
邮递员请求
curl --location --request PUT 'https://XYZ/api/set_user_data' \
--header 'X-Requested-With: XMLHttpRequest' \
--header 'Accept: application/json' \
--header 'Content-Type: application/json' \
--header 'Authorization: Bearer 12|leRLA5yopCLIxe0oN9MMThctqD78iJDjZdZQkcgs' \
--data-urlencode 'email=XYZ@XYZ.FR' \
--data-urlencode 'name=test2'
这意味着在 Postman 术语中没有发送“Params”,发送了 Authorization Bearer 令牌,发送了一些 Headers 并且发送了一些 Body 的 x-www-form-urlencoded 数据。
API 路由
在routes/api.php:
Route::put('/set_user_data', [UserController::class, 'setUserData'])->name('set_user_data');
UserController::setUserData:
public function setUserData(Request $request) {
if(!Auth::check()) {
return 'unauthenticated.';
}
$request->validate([
'email' => 'required|email',
'name' => 'required|string'
]);
// ... update user here but out of topic
}
我试图做的事......或不做
-
一些 Stackoverflow 答案是:发送
POST请求并发送正文_method=PUT。我不想这样做。我真的更喜欢发送PUT请求。因为我正在开发一个 API。这完全证明了我必须使用PUT请求而不是PUT请求这一事实。 -
一些 Stackoverflow 答案是:使用
x-www-form-urlencoded而不是简单的form。它不能解决问题;而且已经是这样了。也许它可以帮助发送图像。 (注意我不想在这里发送任何图片)。
问题
为什么 Laravel 的 validate 找不到我请求的数据,如何解决?
【问题讨论】:
-
您需要发送一个有效的 JSON 请求。 Laravel 只在 Web 请求上需要 PUT 方法,在 API 请求上不需要。
标签: laravel laravel-routing put laravel-api