【问题标题】:Get {"message":"Unauthenticated."} when sending POST request to laravel server向 laravel 服务器发送 POST 请求时获取 {"message":"Unauthenticated."}
【发布时间】:2020-08-17 15:58:40
【问题描述】:

我在使用 sanctum 从 Vue axios 向 laravel 服务器发送 POST 请求时遇到问题。

首先我得到令牌。

我的api.php路线

Route::post('/get_token', function (Request $request) {
    $request->validate([
        'email' => 'required|email',
        'password' => 'required',
        'device_name' => 'required'
    ]);
    $user = User::where('email', $request->email)->first();
    if (! $user || ! Hash::check($request->password, $user->password)) {
        throw ValidationException::withMessages([
            'email' => ['The provided credentials are incorrect.'],
        ]);
    }
    return $user->createToken($request->device_name)->plainTextToken;
});

vue axios

this.$axios.post('/api/get_token', {
    email: this.email,
    password: this.password,
    device_name: this.device_name,
}).then(response=>{...});

当我使用收到的令牌发送 GET 请求时,它可以正常工作

vue axios

this.$axios.get('/api/book/all', {
    headers: {
        "Authorization": 'Bearer ' + this.$store.getters.getToken
    }
}).then(response=>{...})

api.php

Route::middleware('auth:sanctum')->get('/book/all', 'BookController@all');

但是当我尝试发送 POST 请求时,我收到 {"message":"Unauthenticated."} 和 401 错误

vue axios

this.$axios.post('/api/book/add', {
    headers: {
        "Authorization": 'Bearer ' + this.$store.getters.getToken,
    },
    data: {
        title: this.addingTitle,
        author: this.addingAuthor,
    }
})

api.php

Route::middleware('auth:sanctum')->post('/book/add', 'BookController@add');

对不起,我只是一个网络菜鸟,很多东西都不懂,希望你能帮助我。

【问题讨论】:

  • book/add 似乎需要根据您共享的内容进行授权,因此book/all 有效这一事实并不表明只有其他路线存在问题
  • @apokryfos 是的,问题不仅在于book/add,它只是我项目中唯一的发布请求;)如果我尝试在没有令牌的情况下向book/all 发送获取请求,我也得到 {"message":"Unauthenticated."}。抱歉英语不好

标签: php laravel vue.js axios


【解决方案1】:

如果您使用post,则第一个参数是 URL,第二个参数是您发布的数据。在您的情况下,使用它可能更有意义:

this.$axios({
    method: 'POST',
    url: '/api/book/add'
    headers: {
        "Authorization": 'Bearer ' + this.$store.getters.getToken,
    },
    data: {
        title: this.addingTitle,
        author: this.addingAuthor,
    }
})

或者如果你还想继续使用.post,那么:

this.$axios.post('/api/book/add', {
        title: this.addingTitle,
        author: this.addingAuthor,
    }, {
    headers: {
        "Authorization": 'Bearer ' + this.$store.getters.getToken,
    }
})


【讨论】:

  • 非常感谢,没想到问题出在前面
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-12-12
  • 1970-01-01
  • 2016-07-03
  • 2017-05-04
  • 2016-03-08
  • 1970-01-01
  • 2019-03-16
相关资源
最近更新 更多