[{"createTime":1735734952000,"id":1,"img":"hwy_ms_500_252.jpeg","link":"https://activity.huaweicloud.com/cps.html?fromacct=261f35b6-af54-4511-a2ca-910fa15905d1&utm_source=V1g3MDY4NTY=&utm_medium=cps&utm_campaign=201905","name":"华为云秒杀","status":9,"txt":"华为云38元秒杀","type":1,"updateTime":1735747411000,"userId":3},{"createTime":1736173885000,"id":2,"img":"txy_480_300.png","link":"https://cloud.tencent.com/act/cps/redirect?redirect=1077&cps_key=edb15096bfff75effaaa8c8bb66138bd&from=console","name":"腾讯云秒杀","status":9,"txt":"腾讯云限量秒杀","type":1,"updateTime":1736173885000,"userId":3},{"createTime":1736177492000,"id":3,"img":"aly_251_140.png","link":"https://www.aliyun.com/minisite/goods?userCode=pwp8kmv3","memo":"","name":"阿里云","status":9,"txt":"阿里云2折起","type":1,"updateTime":1736177492000,"userId":3},{"createTime":1735660800000,"id":4,"img":"vultr_560_300.png","link":"https://www.vultr.com/?ref=9603742-8H","name":"Vultr","status":9,"txt":"Vultr送$100","type":1,"updateTime":1735660800000,"userId":3},{"createTime":1735660800000,"id":5,"img":"jdy_663_320.jpg","link":"https://3.cn/2ay1-e5t","name":"京东云","status":9,"txt":"京东云特惠专区","type":1,"updateTime":1735660800000,"userId":3},{"createTime":1735660800000,"id":6,"img":"new_ads.png","link":"https://www.iodraw.com/ads","name":"发布广告","status":9,"txt":"发布广告","type":1,"updateTime":1735660800000,"userId":3},{"createTime":1735660800000,"id":7,"img":"yun_910_50.png","link":"https://activity.huaweicloud.com/discount_area_v5/index.html?fromacct=261f35b6-af54-4511-a2ca-910fa15905d1&utm_source=aXhpYW95YW5nOA===&utm_medium=cps&utm_campaign=201905","name":"底部","status":9,"txt":"高性能云服务器2折起","type":2,"updateTime":1735660800000,"userId":3}]
1.在项目根目录下安装jsonserver和axios插件以及全局安装json-server
npm install json-server --save
npm install axios --save
npm install -g json-server
2.在项目根目录下新建数据文件db.json,内容如下:
3.打开packege.json在"scripts"中添加一行
jsonsv是随意取的名字,要注意如果取jsonserver这样的名字有可能会出现报错。
在控制窗口输入 npm run jsonsv 运行服务器,也可以直接输入json-server --watch
db.json运行服务器,就不用在"script"中添加上面那一行,但是每次运行都要输入这么长又不好记的命令有点麻烦。
打开浏览器输入locahost:3000可见到jsonserver的启动页面。
输入localhost:3000/posts可获取到db.json中“posts”的数据。
4.vue的默认端口是8080,而jsonserver的默认端口是3000,所以我们需要配置jsonserver的端口
打开build\webpack.dev.conf.js,插入下面的代码,将jsonserver的监听端口设置为8081。
5.然后我们需要把本地localhost:8080发出的请求转发到localhost:8081,就实现了本地请求数据接口。
打开config\index.js,找到proxyTable{},添加下面代码。
配置完成,输入命令npm run
dev运行服务器,在浏览器同时打开localhost:8080和localhost:8081能成功显示出项目首页和jsonserver的启动页面,那么我们就已经实现了同一个服务器同时运行vue和jsonserver。
6.接下来就是在vue中用axios请求jsonserver上的数据
在main.js中全局注册axios
输入命令npm run
dev运行服务器,浏览器打开localhost:8080,页面上和控制台会显示从/api/post(localhost:8081/posts)请求得到的数据。