一般会在vue.config.js里面设置,在vue-cli3里面隐藏了这个文件,新建一下配置就会全部出来,其中在里面的configureWebpack对象里面的devserver里面新建一个如下的请求,这是一个express代码,代码如下。

   before(app) {
        // 模拟后台服务器express
        app.get("/api/login", function(req, res) {
          const { username, passwd } = req.query;
          console.log(username, passwd);

          if (username == "kaikeba" && passwd == "123") {
            res.json({ code: 1, token: "jilei" });
          } else {
            res.status(401).json({ code: 0, message: "用户名或者密码错误" });
          }
        });
      // 保护接口中间件
        function auth(req, res, next) {
          if (req.headers.token) {
            // 已认证
            next()
          } else {
            // 用户未授权
            res.sendStatus(401)
          }
        }
        
        // 获取登录用户信息
        app.get("/api/userinfo", auth, function(req, res) {
          res.json({ code: 1, data: { name: "tom", age: 20 } });
        });
      }

新建完要重启下vue-cli的测试服务器
如果要在里面设置代理进行跨域操作

module.exports = {
 devServer: {
 // 设置主机地址
 host: 'localhost',
 // 设置默认端口
 port: 8080,
 // 设置代理
 proxy: {
  '/api': {
    // 目标 API 地址
    target: 'http://192.168.1.1:8080/',
    // 如果要代理 websockets
    ws: true,
    // 将主机标头的原点更改为目标URL
     changeOrigin: false
   }
  }
 }
}
Last modification:October 20, 2019
If you think my article is useful to you, please feel free to appreciate