我正在try 使用以下代码创建自定义身份验证控制器:

<?php

namespace App\Http\Controllers;

use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;

class AuthController extends Controller
{
    public function register(Request $request)
    {
        //validate the request
        $request->validate([
            'name' => 'required|string|max:255',
            'email' => 'required|string|email|max:255|unique:users',
            'password' => 'required|string|min:8|confirmed',
        ]);

        $data = $request->all();

        //create new user
        $user = User::create([
            'name' => $data['name'],
            'email' => $data['email'],
            'password' => Hash::make($data['password']),
        ]);

        //return response
        return response()->json(['message' => 'Successfully created user!'], 201);
    }
}

控制器应该在数据库中创建一个新的用户条目,用户模型是Laravel的默认模型,没有进行任何更改.

在我的api.php路径文件中,我设置了以下简单的路径:

<?php

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\AuthController;


Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
    return $request->user();
});

Route::post('/register', [AuthController::class, 'register']);

问题是,当我try 向/api/Register发送POST请求时,Laravel使用默认的html页面进行响应:

Postman response to post request

我到底做错了什么?考虑到这应该只是我的应用程序的后端,所以我不需要设置任何视图

推荐答案

在您的注册方法中,您有验证.如果验证失败,则返回验证错误.因此,您的$REQUEST字段中的某个位置有错误.

Name应该是字符串,email必须是有效的邮箱,并且应该是唯一的,这意味着现有用户都不应该拥有它.对于password,你必须有确认书,我认为这就是问题所在.

您不仅应该将‘name’、‘Email’和‘Password’传递给此GET API路径,还应该传递给‘PASSWORD_CONFIRMATION’字段,该字段包含与‘PASSWORD’字段相同的密码.我建议您删除此规则以简化请求,如下所示:

        //validate the request
        $request->validate([
            'name' => 'required|string|max:255',
            'email' => 'required|string|email|max:255|unique:users',
            'password' => 'required|string|min:8',
        ]);

        

Php相关问答推荐

PHP Array to Powershell exec命令Args

启用额外的WooCommerce产品库存位置

从产品中获取WooCommerce产品属性单选按钮的列表WP_Query

管理员订单列表中的自定义列与WooCommerce 8.6.1一起消失

Laveel Livewire Get Groupby姓名列表

Laravel POST方法返回状态:POST方法上不允许使用405方法

中继器内置中继器的ACF WordPress组

在PHP中读取JSON

按与WooCommerce管理顺序列表中的特定字符串不匹配的特定元值筛选订单

PHP从响应应用程序json获取文件代码和URL

允许客户定义特定WooCommerce产品的价格

打折时更改 Woocommerce 产品名称

将一个表中的行连接为不同表MYSQL中的一列

用自定义代码替换 WooCommerce 单一产品简短描述

在 DateTime 或 DateTimeImmutable 对象上调用modify() 时是否必须使用空格?

使用动态地址和动态文件创建zip文件并获取zip文件链接

使用 Composer 找不到 Google APIClient 类

从图像URL中获取文件扩展名?

我怎样才能在 .htaccess 中有 2 个参数?

使用 GROUP_CONCAT 规范化/转置来自查询的数据