向laravel服务器发送POST请求时,获取{"message":“未经身份验证".} [英] Get {"message":"Unauthenticated."} when sending POST request to laravel server

查看:50
本文介绍了向laravel服务器发送POST请求时,获取{"message":“未经身份验证".}的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从Vue axios向带有圣所的laravel服务器发送POST请求时遇到问题.

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

首先,我得到令牌.

我的 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请求时,它可以正常工作

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

但是当我尝试发送POST请求时,却收到 {"message":未经身份验证."} 和401错误

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.

推荐答案

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

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,
    }
})

或者如果您仍要使用 .post ,则:

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,
    }
})


这篇关于向laravel服务器发送POST请求时,获取{"message":“未经身份验证".}的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆