Vue项目打包后---在nodejs环境中应用并代理跨域
Vue项目打包后—在nodejs环境中应用并代理跨域
使用koa框架部署项目
一、建立web服务文件夹 crmServer
$ mkdir hrServer #建立crmServer文件夹
二、在该文件夹下,初始化npm
$ npm init -y
三、安装服务端框架koa(也可以采用express或者egg)
$ npm i koa koa-static
四、新建public文件夹,copy打包后的dist目录下的文件到hrServer/public
下
五、在根目录下创建app.js
app.js
const Koa = require(koa) const serve = require(koa-static); const app = new Koa(); app.use(serve(__dirname + "/public")); //将public下的代码静态化 app.listen(3333, () => { console.log(CRM项目启动) })
此时,我们可以访问,
此时页面可以出来了
补充
更改路由模式为 history模式,设置基地址
// src/router/index.js 在路由实例中添加 mode: history, base: /admin/, // 配置项目的基础地址
解决history页面访问问题
安装 koa中间件
$ npm i koa2-connect-history-api-fallback
注册中间件
const Koa = require(koa) const serve = require(koa-static); const { historyApiFallback } = require(koa2-connect-history-api-fallback); const path = require(path) const app = new Koa(); // 这句话 的意思是除接口之外所有的请求都发送给了 index.html app.use(historyApiFallback()); // 这里的whiteList是 白名单的意思 app.use(serve(__dirname + "/public")); //将public下的代码静态化 app.listen(3333, () => { console.log(人资项目启动) })
解决生产环境跨域问题
在nodejs中代理
安装跨域代理中间件
$ npm i koa2-proxy-middleware
配置跨越代理
const proxy = require(koa2-proxy-middleware) app.use(proxy({ targets: { // (.*) means anything /prod-api/(.*): { target: 项目服务器地址, //后端服务器地址 changeOrigin: true, pathRewrite: { /prod-api: "" } } } }))
注意:这里之所以用了pathRewrite,是因为生产环境的请求基础地址是 /prod-api,需要将该地址去掉
That is All !
下一篇:
javaweb案例 选中删除和查询功能