【问题标题】:Setting up API with Laravel Passport - why am I getting an unauthorized error?使用 Laravel Passport 设置 API - 为什么我会收到未经授权的错误?
【发布时间】:2020-11-12 03:31:29
【问题描述】:

我正在关注有关构建 Laravel 和 Vue JS Web 应用程序的教程,我有一个问题:

我正在尝试使用 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)

我只是想知道为什么会出现这些错误? 我已经运行了以下命令: '作曲家需要 laravel/护照' php工匠迁移 php工匠护照安装

用户.php


    class User extends Authenticatable
{
    use Notifiable, HasApiTokens;

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

配置/auth.php


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

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

routes.php


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

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>

如果有人有任何想法,请告诉我。我尝试清除配置缓存并包含 csrf 令牌。谢谢,

罗伯特 英国伦敦

【问题讨论】:

  • 我已经尝试过了,我已经将它添加到我的 AppServiceProvider 中的“boot()”函数中: public function boot() { Schema::defaultStringLength(191); \Laravel\Passport\Passport::withoutCookieSerialization();但我仍然收到相同的 401 错误:(

标签: php html laravel axios laravel-passport


【解决方案1】:

确保: 在 $middlewareGroups 下的内核文件中添加 \Laravel\Passport\Http\Middleware\CreateFreshApiToken::class,

在启动功能下将Passport::routes();添加到AuthServiceProvider。

在 routes/api.php 中,将您的路由分组

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

 //Routes here      

 });

【讨论】:

  • 根或引导功能?
  • 修正了错字。
  • 感谢@Ahmed Saleh,所有这些都存在,我已经运行了 npm run:watch 和 php artisan config:cache,但我仍然遇到同样的错误 - 还有其他想法吗?跨度>
  • 能否请您确保您已在 config/auth.php 中将 api 驱动程序更改为“passport”
  • 另外,检查 kernel.php 中的中间件组,在 'api' 下添加 'auth:api'
【解决方案2】:

您应该运行 artisan 命令:php artisan passport:install

【讨论】:

    猜你喜欢
    • 2021-05-25
    • 2010-10-03
    • 2022-07-18
    • 1970-01-01
    • 2020-12-23
    • 2017-04-17
    • 2017-11-26
    • 2021-03-10
    • 2019-01-31
    相关资源
    最近更新 更多