在laravel 5.6的cors与护照和vues js与axios

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了在laravel 5.6的cors与护照和vues js与axios相关的知识,希望对你有一定的参考价值。

我读了很多关于我的cors问题的参考资料,this package会解决所有问题,但直到现在我都试图做任何与此相关的事情并没有得到解决方案。

所以我得到的错误是

Failed to load https://bkcuvue.dev/api/v1/userData: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://bkcuvuelv56.dev' is therefore not allowed access.

这是我的kernel.php

<?php

namespace AppHttp;

use IlluminateFoundationHttpKernel as HttpKernel;

class Kernel extends HttpKernel
{
    /**
     * The application's global HTTP middleware stack.
     *
     * These middleware are run during every request to your application.
     *
     * @var array
     */
    protected $middleware = [
        IlluminateFoundationHttpMiddlewareCheckForMaintenanceMode::class,
        IlluminateFoundationHttpMiddlewareValidatePostSize::class,
        AppHttpMiddlewareTrimStrings::class,
        IlluminateFoundationHttpMiddlewareConvertEmptyStringsToNull::class,
        AppHttpMiddlewareTrustProxies::class,
        BarryvdhCorsHandleCors::class,
    ];

    /**
     * The application's route middleware groups.
     *
     * @var array
     */
    protected $middlewareGroups = [
        'web' => [
            AppHttpMiddlewareEncryptCookies::class,
            IlluminateCookieMiddlewareAddQueuedCookiesToResponse::class,
            IlluminateSessionMiddlewareStartSession::class,
            // IlluminateSessionMiddlewareAuthenticateSession::class,
            IlluminateViewMiddlewareShareErrorsFromSession::class,
            AppHttpMiddlewareVerifyCsrfToken::class,
            IlluminateRoutingMiddlewareSubstituteBindings::class,
            LaravelPassportHttpMiddlewareCreateFreshApiToken::class,
        ],

        'api' => [
            'throttle:60,1',
            'bindings',
        ],
    ];

    /**
     * The application's route middleware.
     *
     * These middleware may be assigned to groups or used individually.
     *
     * @var array
     */
    protected $routeMiddleware = [
        'auth' => IlluminateAuthMiddlewareAuthenticate::class,
        'auth.basic' => IlluminateAuthMiddlewareAuthenticateWithBasicAuth::class,
        'bindings' => IlluminateRoutingMiddlewareSubstituteBindings::class,
        'cache.headers' => IlluminateHttpMiddlewareSetCacheHeaders::class,
        'can' => IlluminateAuthMiddlewareAuthorize::class,
        'guest' => AppHttpMiddlewareRedirectIfAuthenticated::class,
        'throttle' => IlluminateRoutingMiddlewareThrottleRequests::class,
    ];
}

这是从包中发布的配置

return [

    'supportsCredentials' => true,
    'allowedOrigins' => ['*'],
    'allowedOriginsPatterns' => [],
    'allowedHeaders' => ['*'],
    'allowedMethods' => ['*'],
    'exposedHeaders' => [],
    'maxAge' => 0,

];

这是我在api.php的路线

Route::group(['prefix'=>'v1','middleware'=>'auth:api'],function(){
// Route::group(['prefix'=>'v1'],function(){

    // user
    Route::get('/profile', 'UserController@getUser');
    Route::get('/userData', 'UserController@userData');

});

在我的vue js方面,这是我的app.js

import Vue from 'vue';
import Admin from './admin.vue';
import VueRouter from 'vue-router';
import routes from './routes';
import { store } from './store/store';
import Axios from 'axios';
import id from 'vee-validate/dist/locale/id';
import VeeValidate, { Validator } from 'vee-validate';

Validator.localize('id',id); //localization
Vue.use(VueRouter);
Vue.use(VeeValidate, {fieldsBagName: 'formFields'});

window.axios = Axios;
axios.defaults.headers.common = { 'X-Requested-With': 'XMLHttpRequest'};
let token = document.head.querySelector('meta[name="csrf-token"]');

if (token) {
    window.axios.defaults.headers.common['X-CSRF-TOKEN'] = token.content;
} else {
    console.error('CSRF token not found: https://laravel.com/docs/csrf#csrf-x-csrf-token');
}

const router = new VueRouter({
    base: '/admins',
    mode: 'history',
    routes
});

router.beforeEach((to, from, next) => {
    window.scrollTo(0, 0);
    if (to.fullPath !== "/login") {
        axios.get('/api/v1/profile').then(response => {       
            next();
        }).catch(error => {
            router.push('/login');
        })
    }else{
        next();
    }
});

Vue.directive('tooltip', function(el, binding){
    $(el).tooltip({
            title: binding.value,
            placement: binding.arg,
            trigger: 'hover'             
        })
});

export const bus = new Vue();

const app = new Vue({
    store,
    router,
    render: h => h(Admin)
}).$mount('#app');

这是我的login.vue

<template>
    <div class="login-container">
        <!-- Page container -->
        <div class="page-container">
            <!-- Page content -->
            <div class="page-content">
                <!-- Main content -->
                <div class="content-wrapper">

                    <!-- login form -->
                    <div class="panel panel-body login-form">
                        <div class="text-center">
                            <h5 class="content-group">SIMO
                                <small class="display-block">Sistem Informasi Manajemen Organisasi</small>
                            </h5>
                        </div>

                        <message :show="message.show">
                            <p>{{message.content}}</p>
                        </message>

                        <message :show="errors.any()" v-if="submited">
                            <h4>
                                <i class="icon-cancel-circle2"></i> Oops terjadi kesalahan</h4>
                            <ul>
                                <li v-for="error in errors.items">{{error.msg}}</li>
                            </ul>
                        </message>

                        <div class="form-group has-feedback has-feedback-right" :class="{'has-error' : errors.has('Username')}">
                            <div class="input-group">
                                    <div class="input-group-addon">
                                        <i class="icon-user text-muted"></i>
                                    </div>
                                    <input type="text" class="form-control" placeholder="Username" v-model="username" name="Username" v-validate="'required|min:5'" @keyup.enter="login" autofocus>
                            </div>

                            <div class="form-control-feedback" v-if="errors.has('Username')">
                                <i class="icon-cancel-circle2"></i>
                            </div>
                        </div>

                        <div class="form-group has-feedback has-feedback-right" :class="{'has-error' : errors.has('Password')}">
                            <div class="input-group">
                                <div class="input-group-addon">
                                    <i class="icon-lock2 text-muted"></i>
                                </div>
                                <input type="password" class="form-control" placeholder="Password" v-model="password" name="Password" v-validate="'required'"
                              @keyup.enter="login">
                            </div>

                            <div class="form-control-feedback" v-if="errors.has('Password')">
                                <i class="icon-cancel-circle2"></i>
                            </div>
                        </div>

                        <div class="form-group">
                            <button type="button" class="btn btn-primary btn-block" disabled v-if="loading">
                                <i class="icon-spinner2 spinner"></i>
                            </button>
                            <button type="button" class="btn btn-primary btn-block" @click.prevent="login"  v-else>Login
                                <i class="icon-circle-right2 position-right"></i>
                            </button>
                        </div>
                    </div>
                    <!-- /simple login form -->
                </div>
                <!-- /main content -->
            </div>
            <!-- /page content -->
        </div>
        <!-- /page container -->
    </div>
</template>

<script type="text/javascript">
    import Message from "../components/message.vue";
    import Progress from '../assets/plugins/loaders/progressbar.min.js'
    export default {
        components: {
            Message
        },
        data() {
            return {
                username: "",
                password: "",
                loading: false,
                submited: '',
                message: {
                    show: false,
                    className: '',
                    content: ''
                }
            }
        },
        mounted() {
            Progress.progressbar();
        },
        methods: {
            login() {
                this.$validator.validateAll().then((result) => {
                    if(result){
                        this.message.show = false;
                        this.loading = true;
                        axios.post('/login', {
                                username: this.username,
                                password: this.password
                            })
                            .then(response => {
                                this.$router.push('/');
                            }).catch(error => {
                                this.message.show = true;
                                this.message.className = 'bg-danger';
                                if (error.response.status === 422) {
                                    this.message.content = "Username atau password anda salah.";
                                } else {
                                    this.message.content = error.response.data.message;
                                }
                                this.loading = false;
                            });
                            this.submited = false;
                    }else{
                        window.scrollTo(0, 0);
                        this.submited = true;
                    }
                });
            }
        }
    }
</script>
答案

我真的很抱歉,在检查了chrome中的标题响应之后,我只记得在我的vue中我正在配置api路径和那些api路径刚刚引用我的旧laravel 5.4项目之前我正在升级,这就是让事情变得奇怪......

以上是关于在laravel 5.6的cors与护照和vues js与axios的主要内容,如果未能解决你的问题,请参考以下文章

Laravel 5.6 护照未经身份验证

Laravel 护照和 Vue 登录

barryvdh/laravel-cors 配置在 Laravel 5.6 中不起作用;忽略'allowedMethods'

php laravel 5.6级的cors不存在

php Laravel 5.6 CORS中间件

为啥 Laravel 中间件 CORS 不能与 Vue.js 一起使用