英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论