Get {“message”:“Unauthenticated.”} when sending POST request to laravel server

試著忘記壹切 提交于 2021-02-10 14:47:22

问题


I have a problem with sending POST request from Vue axios to laravel server with sanctum.

Firstly I'm getting token.

My route of 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=>{...});

And when I send GET request with received token, it works correctly

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');

But when I try to send POST request, I get {"message":"Unauthenticated."} and 401 error

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');

Sorry, I’m just a noob in web and don’t understand many things, hope you can help me.


回答1:


If you use post then the 1st parameter is the URL and the 2nd one is the data your are posting. In your case it might make more sense to use:

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

or if you want to still use .post then:

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




来源:https://stackoverflow.com/questions/61571669/get-messageunauthenticated-when-sending-post-request-to-laravel-server

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!