axios访问本地json失败

代码如下,用axios发送请求,请求本地写的data.json数据,控制台没打印数据集

<!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">

    <title>Document</title>

</head>

 

<body>

    <div id="app">

        <div v-for="user in memberList">

            {{user.name}}---{{user.age}}

        </div>

    </div>

    <script src="vue.min.js"></script>

    <script src="axios.min.js"></script>

    <script>

        //第一步创建html页面,引入Js,vue和axios

        //第二步编写axios代码

        new Vue({

            el: '#app',

            //固定结构

            data: {//data定义变量和初始值

                //定义空数组

                memberList:[]             

            },

            create(){//页面渲染之前执行

                //调用定义的方法

                this.getList()

            },

            method:{

                //编写具体的方法

                getList(){

                    //使用axios发送ajax请求

                    //axios.提交方式(“请求的连接”),.then(箭头函数)和.catch()

                    axios.get("static\data.json")

                        .then(function(response){

                            //response就是请求后返回的数据

                            console.log(response)

                            this.memberList = response.data.data.items

                            console.log(this.memberList)

                        })//请求成功执行then方法

                        .catch(error =>{

 

                        })//请求失败执行catch方法

                }

            }

        })

    </script>

</body>

 

</html>

chrome不允许访问本地资源,搭建http来访问,或者配置过chrome的启动方法才能访问本地文件

给chrome添加启动参数:--allow-file-access-from-files ,这样本地ajax请求就不会报跨域错误了。(注意如果给chrome添加多个启动参数,每个启动参数“--”之前要有空格隔开,如"C:\Program Files\Google\Chrome\Application\chrome.exe" --enable-file-cookies --allow-file-access-from-files

右键点击chrome桌面快捷方式,属性,添加参数

 

请不要使用file协议打开文件,如果你使用vscode可以在vscode上安装一个LiveServer插件,然后在html页面内通过LiveServer打开HTML文件,同时你的json文件放置在跟你的html同级目录或子目录内就可以访问了。

→_→   你就不能直接import进去吗

您好,我是有问必答小助手,您的问题已经有小伙伴解答了,您看下是否解决,可以追评进行沟通哦~

如果有您比较满意的答案 / 帮您提供解决思路的答案,可以点击【采纳】按钮,给回答的小伙伴一些鼓励哦~~

ps:问答VIP仅需29元,即可享受5次/月 有问必答服务,了解详情>>>https://vip.csdn.net/askvip?utm_source=1146287632