【问题标题】:Validation Error Handing Laravel Sanctum Api in JSON在 JSON 中处理 Laravel Sanctum Api 的验证错误
【发布时间】:2022-01-07 18:13:21
【问题描述】:

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 很重要,后端不需要做任何事情。

【问题讨论】:

  • 这很可能是因为 Accept 标头。你能在控制器中发布dd($request->header('Accept')); 的结果吗?

标签: laravel api rest laravel-sanctum


【解决方案1】:

您不需要自己处理。

只需确保您的请求发送正确的标头:Accept: application/json

这个helps Laravel 知道你想要一个 json 响应而不是重定向(导致 404)。

Sample snippet

【讨论】:

  • 服务器端如何在laravel中接受application/json?
  • @PuneetSharma 它是与请求一起发送到服务器的标头,因此它是客户端
  • 让 y = await fetch("127.0.0.1:8000/api/create-account", { 方法: "POST", 标头: { "Content-Type": "application/json", }, 正文: JSON.stringify( x), }).then(response => response.json());
  • 类似的东西
  • Content-Type改成Accept看看能不能用。
猜你喜欢
  • 2014-12-22
  • 2023-03-29
  • 2020-04-09
  • 2020-08-23
  • 2018-09-13
  • 2017-11-06
  • 2019-03-17
  • 2020-09-09
  • 2020-09-22
相关资源
最近更新 更多