在VSCode中搭建express后端框架

之前是学习了KOA,今天特地研究了一下express

全局安装

cnpm insatll express-generator -g

局部

express --view=ejs <项目名称>

启动项目

http://localhost:3000/

 页面出现上图内容则后端项目创建成功

解决跨域问题

前端项目的端口是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记得要安

扫描二维码关注公众号,回复: 15603652 查看本文章
created() {
    axios({
      url: "/api/index_list/0/data/1",
    }).then((res) => {
      console.log(res);
    });
  },

如果得到如下图200OK就算是成功了

猜你喜欢

转载自blog.csdn.net/weixin_52479225/article/details/127913060