Laravel版本10上验证不起作用。

huangapple go评论70阅读模式
英文:

Validation not working on Laravel version 10

问题

这是我在AuthController中的register方法:

public function register(Request $request)
{
    $request->validate([
        'firstName' => 'required | string',
        'lastName' => 'required | string',
        'email' => 'required | email | unique:users,email',
    ], [
        'email.unique' => '已存在具有此电子邮件的用户',
    ]);
}

我正在使用postman发送API请求。

这是我的routes.php中的API端点:

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

然而,当我使用postman发送POST请求到这个端点时,即使字段为空,也会返回一些HTML内容,响应代码为200。当我在postman中点击预览选项卡时,它显示Laravel主页。

英文:

Here is my register method in my AuthController,

 public function register(Request $request)
 {
    $request->validate([
            'firstName' => 'required | string',
            'lastName' => 'required | string',
            'email'    => 'required | email | unique:users,email',
        ], [
            'email.unique' => 'User with this email already exists',
        ]);
 }

I'm using postman to send the API requests,

This is the API endpoint present in my routes.php,

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

However, when I send the POST request to this endpoint using postman some HTML content with a 200 response code returns back even though the fields are set to empty when sending. When I click the preview tab in postman it shows me Laravel home page.

答案1

得分: 2

if this is in routes.php then when you post through postman before this validation, csrf-token also need to be present else it will redirect back. which is not available in case of postman and you will see the home page as the redirected page.

Try adding header Accept: application/json to get the response in json format.

Also I suggest that the apis must defined in api.php in routes folder to remove session related validation on the api calls

so define your routes in api.php like

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

then call it through post as

http://localhost/project/api/register

英文:

if this is in routes.php then when you post through postman before this validation, csrf-token also need to be present else it will redirect back. which is not available in case of postman and you will see the home page as the redirected page.

Try adding header Accept: application/json to get the response in json format.

Also I suggest that the apis must defined in api.php in routes folder to remove session related validation on the api calls

so define your routes in api.php like

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

then call it through post as

http://localhost/project/api/register

huangapple
  • 本文由 发表于 2023年3月12日 15:44:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/75711715.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定