我正在向http://localhost/projects/webdevlist/public/api/register
发送发布请求,并收到405错误:
Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException
The POST method is not supported for this route. Supported methods: GET, HEAD.
routes \ api.php:
<?php
use Illuminate\Http\Request;
Route::middleware('auth:api')->get('/user', function (Request $request) {
return $request->user();
});
Route::post('/register', 'Api\AuthController@register');
Api \ AuthController.php:
<?php
namespace App\Http\Controllers\Api;
use App\User;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
class AuthController extends Controller
{
public function register(Request $request)
{
$validatedData = $request->validate([
'name' => 'required|max:55',
'email' => 'required|email',
'password' => 'required|confirmed'
]);
$user = User::create($validatedData);
$accessToken = $user->createToken('token')->accessToken;
return response(['user' => $user, 'access_token' => $accessToken]);
}
}
如果我删除了表单验证,那么我可以很好地发布请求,并以这样的方式在邮递员中返回结果。
<?php
namespace App\Http\Controllers\Api;
use App\User;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
class AuthController extends Controller
{
public function register(Request $request)
{
return response()->json([
$request->name,
$request->email,
$request->password,
]);
}
}
但是我的验证有问题。为什么验证会导致我不再能够接受POST
请求?
答案 0 :(得分:2)
您的验证问题是password
字段。
您的规则说它是必需的,并且已确认,但已针对哪个字段进行了确认?
如果尚未添加名称,请添加一个名称为password_confirmation
的字段。
<input type="password" name="password_confirmation" />
然后为password_confirmation
字段添加新规则:
$validatedData = $request->validate([
'name' => 'required|max:55',
'email' => 'required|email',
'password' => 'required|confirmed',
'password_confirmation' => 'required'
]);