首页 > 解决方案 > Vue + axios:已被 CORS 策略阻止

问题描述

我有使用 axios 的 vue 应用程序,首先将 axios 设为默认值: import axios from 'axios'

const token ='xxxxxxxxx'
axios.defaults.headers.common['Access-Control-Allow-Origin'] = '*';
axios.defaults.headers.common['Authorization'] = `Bearer ${token}`;
axios.defaults.baseURL = 'http://xxxxxxxxx/api/v1/'

然后在一个页面中我调用 axios :

<script>
export default {
    data : function () {
        return {
            games : []
        }
    },
    created: async function(){
       await this.axios('games/this',{withCredentials: true,}).then((res)=>  this.games=res.json)  
    }
}
</script>

我收到这个错误from origin 'http://localhost:3001' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource

我从本网站的帖子中尝试了许多解决方案,但都不起作用

标签: vue.jsaxioscors

解决方案


CORS 问题应该在后端解决。如果你使用 Lumen 作为后端,请确保你安装了 Laravel-Cors https://github.com/spatie/laravel-cors 然后在 config/cors.php 文件中设置 allowed_origins 为 *。

...

'allowed_origins' => ['*'],

...

推荐阅读