我正在Laravel 9中创建一个API,在使用FormRequest时会出现此错误。
编辑:我已经尝试过:php artisan route: clear
而且php artisan route: cache
php artisan route:list
POST _ignition/execute-solution ...... ignition.executeSolution › SpatieLaravelIgnition › ExecuteSolutionController
GET|HEAD _ignition/health-check .................. ignition.healthCheck › SpatieLaravelIgnition › HealthCheckController
POST _ignition/update-config ............... ignition.updateConfig › SpatieLaravelIgnition › UpdateConfigController
GET|HEAD api/categories ......................................... generated::lHkZOL5tf3LIcEQ8 › CategoryController@index
POST api/sections ............................................ generated::UOlJ66qvitxlxVFJ › SectionController@store
GET|HEAD api/statuses ............................................. generated::QEy3vMPtQoyTF9ZF › StatusController@index
POST api/surveys .............................................. generated::ugYzFBQ10OqCe15t › SurveyController@store
GET|HEAD api/surveys .............................................. generated::cp4J8q5S2iAURPD9 › SurveyController@index
GET|HEAD api/user .......................................................................... generated::ZAKvw5kCNfZA65gG
GET|HEAD sanctum/csrf-cookie ......................... sanctum.csrf-cookie › LaravelSanctum › CsrfCookieController@show
我的路线
Route::post('/sections', [SectionController::class, 'store']);
我的控制器
class SectionController extends Controller
{
public function store(StoreSectionRequest $request)
{
return $request;
}
}
我的问题是,当我使用StoreSectionRequest时,它会向我抛出错误:
The POST method is not supported for this route. Supported methods: GET, HEAD.
但当我只使用Request时,它可以正常工作。
class SectionController extends Controller
{
public function store(Request $request)
{
return $request;
}
}
这就是它正确工作的方式。
我不明白会发生什么,因为在创建其他路线时,我没有遇到这个问题。
class StoreSectionRequest extends FormRequest
{
public function authorize()
{
return true;
}
public function rules()
{
return [
'title' => 'required | string ',
'description' => 'nullable | string',
'survey_id' => 'required | exists:surveys,id'
];
}
}
包含StoreSectionRequest时,也包含验证。
一个验证错误被抛出,但您可能没有向Laravel指示您需要json响应,而不是重定向到相同路由的GET。
确保您的API请求在头中包含Accept: application/json
,以便Laravel知道它是一个json请求
从这里的评论:如何使用vue和laravel 将数据插入数据库
在控制台上运行php-artisan-route:list。你会得到你的所有路线应用程序。这是Route::post('/section',[SectionController::class,'store'](的列表;路线。通过路线列表,您将了解URI和操作