之前是学习了KOA,今天特地研究了一下express
cnpm insatll express-generator -g
express --view=ejs <项目名称>
页面出现上图内容则后端项目创建成功
前端项目的端口是8080
后端项目的端口是3000
就会存在跨域问题,下面是解决跨域问题的方法
在项目中vue.config.js文件加入
let path=require("path");
module.exports={
//代理
devServer:{
proxy:{
'/api':{
target:"http://localhost:3000",
changeOrigin:true,
pathRewrite:{
'^/api':"/api"
}
}
},
}
}
这时候前后端连接应该是正常的,我用我正在做的一个盲盒手机端小项目测试一下
在server(后端文件夹)中routes文件夹下的index.js文件中加一个get请求
router.get("/api/index_list/0/data/1", function (req, res, next) {
res.send({
code: 0,
data: {
topBar :[
{ id: 0, label: "推荐" },
{ id: 1, label: "SP夜之城" },
{ id: 2, label: "SP改娃" },
{ id: 3, label: "MimiA" },
],
data : [
//这是swiper
{
id: 0,
type: "swiperList",
data: [
{ id: 0, imgUrl: "/images/swiper1.png" },
{ id: 1, imgUrl: "/images/swiper2.png" },
{ id: 2, imgUrl: "/images/swiper3.png" },
],
},
//这是swiper
{
id: 0,
type: "swiperList",
data: [
{ id: 0, imgUrl: "/images/swiper1.png" },
{ id: 1, imgUrl: "/images/swiper2.png" },
{ id: 2, imgUrl: "/images/swiper3.png" },
],
},
//这是icons
{
id: 1,
type: "iconsList",
data: [
{
id: 1,
title: "雷娃改造",
imgUrl: "/images/icons1.png",
}
],
},
//爆款推荐
{
id: 2,
type: "recommendList",
data: [
{
id: 1,
name: "Alika 四季有你",
content: "Alika初代大娃 春夏秋冬",
price: "65",
imgUrl: "/images/recommend1.jpg",
},
{
id: 2,
name: "Alika 四季有你",
content: "Alika初代大娃 春夏秋冬",
price: "65",
imgUrl: "/images/recommend1.jpg",
}
],
},
//猜你喜欢
{
id: 3,
type: "likeList",
data: [
{
id: 1,
imgUrl: "./images/like1.jpg",
name: "Skullpanda改娃 游乐园迷镜 陶瓷感",
price: 150,
},
{
id: 2,
imgUrl: "./images/like1.jpg",
name: "Skullpanda改娃 游乐园迷镜 陶瓷感",
price: 150,
}
],
},
],
},
});
});
前端文件夹中使用,用了axios记得要安
created() {
axios({
url: "/api/index_list/0/data/1",
}).then((res) => {
console.log(res);
});
},
如果得到如下图200OK就算是成功了