简体   繁体   English

使用 Laravel Passport 设置 API - 为什么会出现未经授权的错误?

[英]Setting up API with Laravel Passport - why am I getting an unauthorized error?

I am following along with a tutorial on building Laravel and Vue JS web apps, and I have a question:我正在关注有关构建 Laravel 和 Vue JS web 应用程序的教程,我有一个问题:

I am trying to build an api using Laravel Passport, and I am getting the following errors:我正在尝试使用 Laravel Passport 构建 api,但出现以下错误:

Failed to load resource: the server responded with a status of 401 (Unauthorized)
app.js:699 Uncaught (in promise) Error: Request failed with status code 401
    at createError (app.js:699)
    at settle (app.js:960)
    at XMLHttpRequest.handleLoad (app.js:168)

I just wondered why these errors might be occuring?我只是想知道为什么会出现这些错误? I have run the following commands: 'composer require laravel/passport' php artisan migrate php artisan passport install我已经运行了以下命令:'composer require laravel/passport' php artisan migrate php artisan passport install

User.php用户.php


    class User extends Authenticatable
{
    use Notifiable, HasApiTokens;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password',
    ];

config/auth.php config/auth.php


    'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'users',
        ],

        'api' => [
            'driver' => 'passport',
            'provider' => 'users',
            'hash' => false,
        ],
    ],

routes.php路线.php


    Route::post('/categories/upsert', 'CategoryController@upsert');

index.blade.php index.blade.php


    <template>
    <form>
        <a @click="addCategory" class="add">+ Add Category</a>
        <div v-for="(category, index) in categories" :key="category.id">
            <input type="text" v-model="category.name"> {{/* inputs will use two way binding with v-model */}}
            <input type="number" v-model="category.display_order">
            <a @click="removeCategory(index)" class="remove">delete</a>
            <div>
                <img v-if="category.image" :src="` /images/${category.image}`" width="100">
                <label v-else>Image: </label>
                <input type="text" v-model.lazy="category.image">
            </div>
            <hr>
        </div>
    </form>
</template>

    <script>
        export default {
            props: ['initialCategories'],
            data() {
                return {
                    categories: _.cloneDeep(this.initialCategories) /* Cloned to avoid mutating the prop */
                };
            },
            created() {
                axios.post('/api/categories/upsert');
            },
            methods: {
                removeCategory(index) {
                    if (confirm('Are you sure?')){
                        this.categories.splice(index, 1);
                    }
                },
                addCategory() {
                    this.categories.push({
                        id: 0,
                        name: '',
                        image: '',
                        display_order: this.categories.length + 1
                    });
                    this.nextTick(() => {
                        window.scrollTo(0, document.body.scrollHeight);
                        this.$refs[''][0].focus();
                    });
                }
    
            }
        }
    </script>

Please let me know if anyone has any ideas.如果有人有任何想法,请告诉我。 I have tried clearing the configuration cache and including a csrf token.我尝试清除配置缓存并包含 csrf 令牌。 Thanks,谢谢,

Robert London, UK英国罗伯特伦敦

You should run artisan command: php artisan passport:install您应该运行工匠命令: php artisan passport:install

Make sure to: Add \Laravel\Passport\Http\Middleware\CreateFreshApiToken::class, to you Kernel file under $middlewareGroups.确保:将\Laravel\Passport\Http\Middleware\CreateFreshApiToken::class,添加到 $middlewareGroups 下的 Kernel 文件中。

Add Passport::routes();添加Passport::routes(); to AuthServiceProvider, under boot function.到 AuthServiceProvider,在启动 function 下。

in routes/api.php, group your routes under在 routes/api.php 中,将您的路线分组

Route::middleware('auth:api')->group(function () {    

 //Routes here      

 });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么我在 Microsoft Graph API 调用中收到“401 Unauthorized”? - Why am I Getting "401 Unauthorized" for Microsoft Graph API Call? Laravel 6 护照中的未经授权的 401 错误 - Unauthorized 401 error in laravel 6 passport 为什么在将此数组设置为类时出现语法错误? - Why am I getting a syntax error in setting this Array into a class? 为什么我在Laravel中遇到此错误:PHP Catchable致命错误? - Why am I getting this error with Laravel: PHP Catchable Fatal Error? 为什么我在尝试使用 Laravel 基本身份验证登录时不断收到 401 Unauthorized 错误? - Why I keep getting 401 Unauthorized error when trying to login with Laravel basic Auth? 为什么我从 api 和 api 资源管理器收到 500 错误 - Why am I getting a 500 error from api and api explorer 为什么在Laravel Framework中出现此内部服务器错误? - Why am I getting this Internal Server Error in the Laravel Framework? 不明白为什么我会收到这个Laravel照亮错误 - Do not understand why I am getting this Laravel Illuminate Error 为什么我在Laravel中收到“未定义[Route [/ login]的错误]”? - Why am i getting “Route [/login] not defined error” in Laravel? 为什么在 .htaccess 中出现此 laravel url 路由错误? - Why am I getting this laravel url routing error in .htaccess?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM