Node 本地运行 Vue 打包项目

express 启动服务

const express = require("express")
const app = express()
const host = 127.0.0.1
const port = 8105
// 静态文件路径
app.use(express.static("./dist"))

// 启动服务监听端口
app.listen(port, function (err) {
          
   
  if (err) {
          
   
    console.log(err)
  } else {
          
   
    console.log("应用实例访问地址为 http://%s:%s", host, port)
  }
})

history 路由模式

const history = require("connect-history-api-fallback")
app.use(history())

接口代理

const proxyConfig = {
          
   
  // 代理前缀
  "/prod-api": {
          
   
    target: "http://www.xxx.com", // 代理接口地址
    changeOrigin: true,
    pathRewrite: {
          
   
      // 重写规则
      "/prod-api": ""
    }
  }
}
// 对象循环插入代理
for (let key in proxyConfig) {
          
   
  app.use(key, createProxyMiddleware(proxyConfig[key]))
}

整体代码

"use strict"
const express = require("express")
const history = require("connect-history-api-fallback")
const {
          
    createProxyMiddleware } = require("http-proxy-middleware")
const app = express()
const host = 127.0.0.1
const port = 8105

const proxyConfig = {
          
   
  "/prod-api": {
          
   
    target: "http://www.xxx.com",
    changeOrigin: true,
    pathRewrite: {
          
   
      "/prod-api": ""
    }
  }
}
for (let key in proxyConfig) {
          
   
  app.use(key, createProxyMiddleware(proxyConfig[key]))
}
app.use(history())
// html 目录存放打包的代码
app.use(express.static("./dist"))
module.exports = app.listen(port, function (err) {
          
   
  if (err) {
          
   
    console.log(err)
  } else {
          
   
    console.log("应用实例,访问地址为 http://%s:%s", host, port)
  }
})
经验分享 程序员 微信小程序 职场和发展