首页 > 解决方案 > Laravel 和 VueJs(Vuetify) 错误:MethodNotAllowedHttpException

问题描述

在我尝试使用 Laravel API 身份验证之前一切正常。现在一些 GET 方法给出 MethodNotAllowedHttpException 并说允许的方法是 POST,HEAD,而对于 post 方法,它说允许的方法是 GET,Head。

这是我的 Vue 组件中的 axios 请求

axios.post('api/save_post?api_token='+api_token, this.post)
    .then(response => {
      console.log(this.user);
      this.success = response.data.message; 
      this.post.title=" ";
      this.post.content=" ";
    })
    .catch(err=>{
        this.error = err
        //this.error = 'Error in saving post, please try again'
    });   

这是我在 routes/api.php 中的路线

 Route::middleware('auth:api')->post('save_post','Api\KnowledgeHubController@index')->name('savePost');

将此包含在我的welcome.blade.php 文件中

meta name="csrf-token" content="{{ csrf_token() }}">

在 meta 之前有 < 所以这不是错误。

控制器功能

public function index(Request $request)
{
    $response = KnowledgeHub::create([
        "title"     => $request['title'],
        "content"   => $request['content'],
        "author_id" => $request['author_id'],
    ]);
    if($response)
    {
        return response()->json(['message'=>'Post published Successfully','response'=>$response],200);
    }
    return response()->json(['message'=>'Error in publishing post','response'=>$response],400);
}

我尝试过的一些 解决方案

标头中包含 1 的 csrf 令牌意味着在我的主文件中(welcome.blade.php)

2-尝试以不同的方式将api_token传递给axios.post

3-run php artisan route:cache

这是php artisan route:list的结果

  POST     | api/save_post            | savePost        | App\Http\Controllers\Api\KnowledgeHubController@index            | api,auth:api 

标签: vuetify.jslaravel-6

解决方案


你可以从你的 vue 应用程序外部调用路由吗?

如果你 100% 认为一切都是正确的:

  1. 尝试将以下标头添加到您的 axios-request:
const headers = {
  'Content-Type': 'application/json'
}

axios.post('api/save_post?api_token='+api_token, this.post, headers)
    .then(response => {
      console.log(this.user);
      this.success = response.data.message; 
      this.post.title=" ";
      this.post.content=" ";
    })
    .catch(err=>{
        this.error = err
        //this.error = 'Error in saving post, please try again'
    });  

还是行不通?

  1. 尝试使用 POSTMAN 之类的程序访问路线
  2. 清除 Laravel 缓存
php artisan cache:clear
php artisan route:cache

推荐阅读