前端:
打开
运行 npm run build 得到 dist 文件夹
后端 Express 喜欢的写法
index.js
注这个就是接包dist目录的:
app.use(express.static('dist'))
// dist 是项目的打包资源路径,一般为根目录下dist
const express = require('express') //require函数引入express包
const app = express() //调用函数
// const routes = require('./routes/index'); //引入路由模块
const fs = require('fs');
// const path = require('path');
const hostname = 'localhost';
const port = 3000;
//实现静态资源服务
// app.use(express.static('./')) //public就是静态资源的根目录,静态资源放于此文件夹
app.use(express.static('dist')) // dist 是项目的打包资源路径,一般为根目录下dist
//中间件
app.use((req,resp,next) => {
//中文乱码处理
resp.header('Content-Type','text/html;charset=utf-8');
next();
});
app.use((req,resp,next) => {
//跨域设置
resp.header("Access-Control-Allow-Credentials", true);
resp.header("Access-Control-Allow-Origin", "*");
resp.header("Access-Control-Allow-Headers", "X-Requested-With");
resp.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
resp.header("X-Powered-By", ' 3.2.1');
resp.header("Content-Type", "application/json;charset=utf-8");
next();
});
const path = require('path');
app.engine('html', require('express-art-template'));
//添加解析参数模块,能够解析POST方式提交的参数
const bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({extended:true}));
app.use(bodyParser.json());
app.get('/list', function (req, res) {
fs.readFile( __dirname + "/" + "./db/sdata.json", 'utf8', function (err, data) {
// console.log( data );
res.end( data );
});
})
// app.use(routes); //挂载路由到app服务中
app.listen(3000, () => { //创建监听
console.log(`server is running at http://${hostname}:${port}/`);
console.log('服务器启动成功...')
})
配置文件 package.json 复制下来 ,运行 npm i 或npm install
{
"name": "vue-test",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "node index.js",
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"body-parser": "^1.20.2",
"express": "^4.18.2",
"express-art-template": "^1.0.1"
}
}
再运行Node.js Express
命令:npm start
Vue项目 打包 后也可用:
npm i serve (npm install -g serve)
serve dist (运行打包dist目录)
React 项目 打包:
yarn build (打包React项目)