1、解决跨域问题
前端端口号为8080,后端为3000,所以在前端的vue.config.js文件中,添加
devServer: {
proxy: {
"/api": {
target: "http://localhost:3000",
changeOrigin: true,
pathRewrite: {
"^/api": "/api",
},
},
},
},
并在前端安装npm i axios -S
2、后端编写接口
在routes文件下的index.js中编写
router.get("/api/index_list/0/data/1", function (req, res, next) {
res.send({
code: 0,
data: {
topBar: [
{ id: 0, label: "推荐" },
{ id: 1, label: "大红袍" },
{ id: 2, label: "铁观音" },
{ id: 3, label: "绿茶" },
{ id: 4, label: "普洱" },
{ id: 5, label: "茶具" },
{ id: 6, label: "花茶" },
],
},
});
});
3、前端调用接口
这里可以将axiso二次封装juejin.cn/post/713339…
import axios from "axios";
created() {
this.getData();
},
methods: {
async getData() {
let res = await axios({
url: "/api/index_list/0/data/1",
});
console.log(res);
//冻结数据
- 不能添加新属性
- 不能删除已有属性
- 不能修改已有属性的值
- 不能修改原型
- 不能修改已有属性的可枚举性、可配置性、可写性
this.items = Object.freeze(res.data.data.topBar);
},
},
4、结果展示
后端向前端发送的数据在data中