作者: 文章来源:
本文原地址:https://www.mimiwuqi.com/webqianduan/195649.html
目录文章目录在前端开发过程中,可能会要对发布到生产的包做验证或者要本地运行一个开源的包的实例,这时候就需要在本地启动一个前端服务,一般有以下两种方式。

通过VsCode去安装插件LiveServer,然后打开静态工程,点击右下角的 Live Server 按钮 即可运行工程
使用express结合http-proxy-middleware来代理请求运行静态工程
1. 在项目根目录运行命令,初始化工程
npm init -y
2. 然后安装库nodemon、express、http-proxy-middleware、mime-types
| 工具 | 介绍 |
|---|---|
| nodemon | 是一个工具,可在检测到目录中的文件更改时自动重新启动 Node 应用程序,从而帮助开发基于 Node.js 的应用程序。 |
| express | 适用于 Node.js 的快速、不拘一格、简约的 Web 框架。 |
| mime-types | 帮助 Node.js 程序识别 mime-types 类型的插件 |
| http-proxy-middleware | http 代理中间件,使 Node.js 代理变得简单。轻松配置 connect、express、next.js 等代理中间件。 |
安装
npm i nodemon express http-proxy-middleware mime-types -D
3. 编写入口文件app.js
const express = require('express')
const path = require('path')
const mine = require('mime-types')
const { createProxyMiddleware } = require('http-proxy-middleware')
const app = express();
const gateWayProxy = createProxyMiddleware('/api', {
target: 'http://172.18.0.197',// 设置要代理的目标服务器
changeOrigin: true, // 启用跨域
// pathRewrite: {
// '^/api': '',// 将请求路径中的'/api'替换为空白
// },
});
// 使用代理中间件
app.use(gateWayProxy);
// 使用静态文件中间件处理静态文件请求
app.use(express.static(path.join(__dirname), {
setHeaders: (res, path) => {
// 根据文件扩展名设置正确的 MIME 类型
const mimeType = mine.lookup(path);
// console.log(mimeType)
if (mimeType) {
res.setHeader('Content-Type', mimeType);
}
}
}))
// 处理根路径请求,发送 index.html
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, 'index.html'));
})
const port = 3001;
app.listen(port, () => {
console.log(`Server is running on port ${port}`);
});
4. 在 package.json 文件中的 scripts 节点中添加运行脚本
{
"scripts":{
"dev":"nodemon app.js"
}
}
5. 执行命令,启动静态工程
npm run serve
以上就是前端如何启动一个静态的前端工程的服务方法的详细内容,更多请关注www.mimiwuqi.com的其它相关文章!
更多 建站教程 请访问 https://www.mimiwuqi.com/webqianduan/