【问题标题】:Vue + axios : has been blocked by CORS policyVue + axios:已被 CORS 策略阻止
【发布时间】:2021-10-13 09:44:48
【问题描述】:

我有使用 axios 的 vue 应用,首先将 axios 设为默认值: 从'axios'导入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.js axios cors


【解决方案1】:

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

...

'allowed_origins' => ['*'],

...

【讨论】:

  • 我更容易解决它,只需将header('Access-Control-Allow-Origin: *'); header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS'); 添加到公共文件夹的 index.php 中
猜你喜欢
  • 2020-08-27
  • 2018-07-20
  • 2021-12-25
  • 2019-10-01
  • 2020-06-02
  • 2021-01-07
  • 1970-01-01
  • 1970-01-01
  • 2019-08-05
相关资源
最近更新 更多