Laravel 通常使用以下方法進行請求驗證。
$request->validate([
'name' => ['required', 'string', 'max:255'],
'email' => ['required', 'string', 'email', 'max:255', 'unique:users', 'required_without_all:phone'],
'password' => ['required', 'confirmed', Rules\Password::defaults()],
'phone' => ['required', 'string', 'max:13', 'unique:users', 'required_without_all:email'],
]);
此方法僅添加可以使用刀片檔案訪問的 $error 變數,因為它僅在服務器上呈現。但是現在我正在使用它只是顯示 404 的 api Sanctum。我猜它只是重定向回請求,而 $error 是只能使用 PHP 訪問的會話。
有解決辦法
$validator = Validator::make($request->all(), [
'name' => ['required', 'string', 'max:255'],
'email' => ['string', 'email', 'max:255', 'unique:users', 'required_without_all:phone'],
'password' => ['required', 'confirmed', Rules\Password::defaults()],
'phone' => ['string', 'max:13', 'unique:users', 'required_without_all:email'],
]);
if ($validator->fails()) {
return response()->json($validator->errors());
}
那只是添加額外的行,我不希望每次都使用此行。有人可以幫我編輯驗證功能,它只回傳任何 $error 作為 json。
澄清答案
我是自我認證的菜鳥,讓我讓它像我的大腦可以使用 fetch 理解一樣
let y = await fetch("http://127.0.0.1:8000/api/register", {
method: "POST", // or 'PUT'
headers: {
"Accept" : "application/json",
"Content-Type": "application/json",
},
body: JSON.stringify(x),
}).then(response => response.json());
console.log(y);
我認為這是一種錯誤的方式,因為有 {"Accept":application/json", "Content-Type": "application/json",} 并且 Accept 很重要,后端不需要做任何事情。
uj5u.com熱心網友回復:
你不需要自己處理這個。
只要確保您的請求發送正確的標頭: Accept: application/json
這有助于Laravel 知道你想要一個 json 回應而不是重定向(導致 404)。
示例片段
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/406317.html
標籤:
