首页 > 解决方案 > 将 JSON 文件导入被 CORS 策略阻止的 Vue 项目

问题描述

在我开始构建的使用 CDN 中的 Vue 的 Vue 应用程序中,我无法通过控制台错误:

CORS 策略已阻止从源“null”访问“file:///C:/files/development/vue/reading_schedule/json/books.json”处的脚本:跨源请求仅支持协议方案:http , 数据, chrome, chrome-extension, chrome-untrusted, https.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <script src="https://cdn.jsdelivr.net/npm/vue"></script>
</head>
<body>
    <div id="app">
       <div>{{ title }}</div>
    </div>

    <script type="module">
        import * as books from './json/books.json';

        new Vue ({
            el: "#app",
            data() {
                return {
                    title: 'Reading Schedule'
                }
            },
            created() {
                document.title = this.title;
                // console.log(books);
            },
            methods: {

            }
        });
    </script>
</body>
</html>

到目前为止,我的 Vue 应用程序开发经验一直是在 Vue CLI 中创建应用程序并将 JSON 导入到这些应用程序中,并且没有 CORS 策略控制台错误。

是否有可能让上面的代码以某种方式工作?

标签: vue.jsimportcors

解决方案


您可以使用插件进行开发:

https://chrome.google.com/webstore/detail/cors-unblock/lfhmikememgdcahcdlaciloancbhjino

但建议您配置一个实际发送 cors 标头的 api 端点。看:

https://medium.com/js-dojo/how-to-deal-with-cors-error-on-vue-cli-3-d78c024ce8d3


推荐阅读