Laravel API:此路由不支持POST方法。支持的方法:GET,HEAD

时间:2019-11-09 16:00:09

标签: php laravel rest post laravel-passport

我正在向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请求?

这是我的POST请求: enter image description here

1 个答案:

答案 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'
]);