web前端常用的五种方式搭建本地静态html页面服务器
方式一:live-server
live-server是一款npm工具,可以在项目目录启动一个node服务,然后直接在浏览器中预览,并且自动全局监听实时更新。
两种安装方式:
全局安装 npm i live-server -g
本地安装 npm i live-server --save-dev
直接使用live-server
首先在项目下npm初始化:npm init -y;
然后可以选择全局安装或者本地安装live-server,然后在package.json的scripts属性中添加如下代码:
"scripts": {
"server": "live-server ./ --port=8181 --host=localhost --proxy=/api:http://www.abc.com/api/"
}
其中包括了代理设置proxy。
然后npm run server执行下就会自动打开当前工程,默认指向index.html页面。
使用node
首先本地安装live-server,执行如下指令:
npm i live-server --save-dev
然后在该项目下新建一个build.js,代码如下:
var liveServer = require("live-server");
var params = {
port: 8181,
host: "localhost",
open: true,
file: "index.html",
wait: 1000,
logLevel: 2,
proxy: [['/api','http://www.abc.com/api/']]
};
liveServer.start(params);
最后在package.json的scripts下添加如下代码:
"scripts": {
"dev": "node build.js"
}
最后执行npm run dev就启动了本地静态页面,路径即是:http://localhost:8081/
详细参考地址:https://www.npmjs.com/package/live-server
方式二:http-server
全局安装http-server
npm i -g http-server
用法:
http-server [path] [options]
其中的path默认指向工程路径下的./public,如果不存在那么使用./。
options就是常见的配置,比如端口、代理地址等,常用配置:
- -p or --port Port to use (defaults to 8080). It will also read from process.env.PORT. (设置端口)
- -a Address to use (defaults to 0.0.0.0) (设置访问地址)
- -P or --proxy Proxies all requests which can't be resolved locally to the given url. e.g.: -P http://someurl.com(设置代理地址)
- -o [path] Open browser window after starting the server. Optionally provide a URL path to open. e.g.: -o /other/dir/ (默认打开浏览器)
cmd进入静态目录工程,可执行如下操作:
http-server ./ -o --port 8085 --proxy http://192.168.11.120:8888/
当然该条命令也可以缩写成如下:
hs ./ -o -p 8085 -P http://192.168.11.120:8888/
我们也可以初始化package.json,执行npm init -y,然后在package.json中的scripts字段中添加如下代码:
"scripts": {
"dev": "http-server ./ -o --port 8089 --proxy http://192.168.11.120:8888/"
}
最后执行npm run dev 也是一样的,使用http-server主要缺点是不能使浏览器自动刷新。
官网github地址:https://github.com/http-party/http-server
方式三:express搭建
使用express简单搭建
使用express搭建前端静态页面环境,在工程下新建build文件夹,建一个dev.js(开发环境启动文件)以及index.js(配置文件、如端口)。
我们只需要安装express以及http-proxy-middleware即可,如下:
npm i express http-proxy-middleware -D
index.js代码:
module.exports = {
port: 8081,
host: 'localhost',
proxyTable: [{
api: '/api',
target: 'http://192.168.1.112:8081/' }]
}
dev.js代码如下:
const express = require('express');
const { createProxyMiddleware } = require('http-proxy-middleware');
const {port = 8080,proxyTable = []} = require('./index.js');
const app = express();
app.use('/', express.static('./')); // 设置静态资源访问路径
proxyTable.forEach((item) => app.use(createProxyMiddleware(item.api, {
target: item.target, // 目标服务器 host
changeOrigin: true, // // 默认false,是否需要改变原始主机头为目标URL
ws: true // 是否代理websockets
})))
app.listen(port,() => {
console.log(`listen:${port}`);
})
在package.json中配置启动快捷键,如下:
"scripts": {
"dev": "node config/dev.js"
}
运行npm run dev 即可启动本地服务器,本地运行localhost:8081即可(默认运行工程下的静态文件index.html),如果需要方法其他静态页面添加相应路径即可。
其中http-proxy-middleware实际就是将http-proxy封装,使用起来更加方便简单,老版本http-proxy-middleware参考:http-proxy-middleware使用方法和实现原理(源码解读),其中新版本的http-proxy-middleware使用方式参考github
使用browser-sync实现热更新优化
代码如下:
const express = require('express');
const path = require('path');
const timeout = require('connect-timeout');
const { createProxyMiddleware } = require('http-proxy-middleware');
const { port = 8080, proxyTable = [], host = 'localhost' } = require('./index.js');
const app = express();
const pathname = path.resolve(__dirname, '../');
const bs = require('browser-sync').create('server');
app.use(timeout(60 * 1e3));
app.use((req, res, next) => {
if (!req.timedout) next();
});
app.use('/', express.static(`${pathname}`)); // 设置静态资源访问路径
proxyTable.forEach((item) => app.use(createProxyMiddleware(item.api, {
target: item.target, // 目标服务器 host
changeOrigin: true, // // 默认false,是否需要改变原始主机头为目标URL
ws: true // 是否代理websockets
})))
app.listen(port, () => {
bs.init({ // 开始一个Browsersync代理
proxy: `http://${host}:${port}`,
notify: true, // 通知
port: 8085,
// files: ['**'] // files 必须带上,不带上修改文件不会刷新;可以指定文件类型、文件等方式
files: [`${pathname}/resources/**/*.html`,`${pathname}/index.html`,`${pathname}/public/**/*.js`,`${pathname}/public/**/*.css`]
})
})
当然也可以用watch方法监听文件的变化,更改代码如下:
const express = require('express');
const path = require('path');
const timeout = require('connect-timeout');
const { createProxyMiddleware } = require('http-proxy-middleware');
const { port = 8080, hotUpdate = false, proxyTable = [], host = 'localhost' } = require('./index.js');
const app = express();
const pathname = path.resolve(__dirname, '../');
const bs = require('browser-sync').create('server');
app.use(timeout(60 * 1e3));
app.use((req, res, next) => {
if (!req.timedout) next();
});
app.use('/', express.static(`${pathname}`)); // 设置静态资源访问路径
proxyTable.forEach((item) => app.use(createProxyMiddleware(item.api, {
target: item.target, // 目标服务器 host
changeOrigin: true, // // 默认false,是否需要改变原始主机头为目标URL
ws: true // 是否代理websockets
})))
bs.watch(`${pathname}/resources/**/*.html`).on("change", bs.reload);
bs.watch(`${pathname}/index.html`).on("change", bs.reload);
bs.watch(`${pathname}/public/**/*.js`, function(event, file) {
if (event === 'change') {
bs.reload('*.js')
}
})
bs.watch(`${pathname}/public/**/*.css`, function(event, file) {
if (event === 'change') {
bs.reload('*.css')
}
})
app.listen(port, () => {
bs.init({ // 开始一个Browsersync代理
proxy: `http://${host}:${port}`,
notify: true, // 通知
port: 8085
})
})
注:Browsersync让浏览器实时、快速响应文件变化并自动刷新,Browsersync说明文档
方式四:使用node内置模块http启动服务
const http = require('http');
const fs = require('fs');
const path = require('path');
const httpProxy = require('http-proxy');
const childProcess = require('child_process'); // 可自动打开浏览器
const filepath = path.resolve(__dirname,'./');
const proxy = httpProxy.createProxyServer(); // 创建代理服务器
const {proxyTable = []} = require('./config/index.js');
http.createServer(function(req,res){
fs.readFile(filepath + req.url,function(err,data) {
proxyTable.forEach((item) => {
if(req.url.indexOf(item.api) !== -1) { // 匹配上接口代理
proxy.web(req,res,{target: item.target});
proxy.on('error',function(e) { // 代理失败处理
console.log(e);
})
} else {
if(err) {
res.writeHeader(404,{'content-type': 'text/html;charset="utf-8"'});
res.write('<h1>404错误</h1><p>你访问的页面/内容不存在</p>');
res.end();
} else {
res.write(data);
res.end();
}
}
})
})
}).listen(8080,() => {
console.log('服务启动了');
});
childProcess.exec('start http://localhost:8080/index.html');
然后在地址栏输入localhost:8080/index.html (其中我的index.html就放在根路径,根据具体路径填写)
换一种方式:
const http = require('http');
const fs = require('fs');
const path = require('path');
const httpProxy = require('http-proxy');
const childProcess = require('child_process'); // 可自动打开浏览器
const filepath = path.resolve(__dirname,'./');
const proxy = httpProxy.createProxyServer(); // 创建代理服务器
const {proxyTable = []} = require('./config/index.js');
const server = new http.Server();
server.on('request',function(req,res){
fs.readFile(filepath + req.url,function(err,data) {
proxyTable.forEach((item) => {
if(req.url.indexOf(item.api) !== -1) { // 匹配上接口代理
proxy.web(req,res,{target: item.target});
proxy.on('error',function(e) { // 代理失败处理
console.log(e);
})
} else {
if(err) {
res.writeHeader(404,{'content-type': 'text/html;charset="utf-8"'});
res.write('<h1>404错误</h1><p>你访问的页面/内容不存在</p>');
res.end();
} else {
res.write(data);
res.end();
}
}
})
})
})
server.listen(8080,() => {
console.log('服务启动了');
});
childProcess.exec('start http://localhost:8080/index.html');
方式五:Nginx配置
conf主要的配置代码:
http {
# nginx负载均衡配置
upstream dynamic_balance {
#ip_hash;
server 192.168.100.123: 8081;
}
# 省略其他
server {
listen 80;
server_name localhost;
#访问工程路径
root website;
index index.html index.htm;
#转发把原http请求的Header中的Host字段也放到转发的请求
proxy_set_header Host $host;
#获取用户真实IP
proxy_set_header X - real - ip $remote_addr;
proxy_set_header X - Forwarded - For $proxy_add_x_forwarded_for;
#接口转发
location /base/ {
proxy_pass http: //dynamic_balance;
}
#启用history模式( 什么请求都只返回index.html)
location / {
try_files $uri $uri / /index.html;
}
}
}
参考
web前端常用的五种方式搭建本地静态html页面服务器的更多相关文章
- XFire构建web service客户端的五种方式
这里并未涉及到JSR 181 Annotations 的相关应用,具体的三种方式如下 ① 通过WSDL地址来创建动态客户端 ② 通过服务端提供的接口来创建客户端 ③ 使用Ant通过WSDL文件来生成客 ...
- 五种方式让你在java中读取properties文件内容不再是难题
一.背景 最近,在项目开发的过程中,遇到需要在properties文件中定义一些自定义的变量,以供java程序动态的读取,修改变量,不再需要修改代码的问题.就借此机会把Spring+SpringMVC ...
- Android数据存储五种方式总结
本文介绍Android平台进行数据存储的五大方式,分别如下: 1 使用SharedPreferences存储数据 2 文件存储数据 3 SQLite数据库存储数据 4 使用Cont ...
- 实现web数据同步的四种方式
http://www.admin10000.com/document/6067.html 实现web数据同步的四种方式 1.nfs实现web数据共享 2.rsync +inotify实现web数据同步 ...
- tomcat的虚拟目录映射常用的几种方式
我们在项目部署的时候,可以采用多种方式,接下来我们将在实际中比较常用的几种方式总结如下. 1.可以直接将我们的项目丢到tomcat的webapps目录下,这样当tomcat重启的时候,我们就可以访 ...
- js页面跳转常用的几种方式(转)
js页面跳转常用的几种方式 转载 2010-11-25 作者: 我要评论 js实现页面跳转的几种方式,需要的朋友可以参考下. 第一种: 复制代码代码如下: <script langu ...
- 【开发笔记】- Java读取properties文件的五种方式
原文地址:https://www.cnblogs.com/hafiz/p/5876243.html 一.背景 最近,在项目开发的过程中,遇到需要在properties文件中定义一些自定义的变量,以供j ...
- linux下实现web数据同步的四种方式(性能比较)
实现web数据同步的四种方式 ======================================= 1.nfs实现web数据共享2.rsync +inotify实现web数据同步3.rsyn ...
- Android_安卓为按钮控件绑定事件的五种方式
一.写在最前面 本次,来介绍一下安卓中为控件--Button绑定事件的五种方式. 二.具体的实现 第一种:直接绑定在Button控件上: 步骤1.在Button控件上设置android:onClick ...
- javaScript中定义类或对象的五种方式
第一种方式: 工厂方法 能创建并返回特定类型的对象的工厂函数(factory function). function createCar(sColor){ var oTempCar = new Obj ...
随机推荐
- SQL Server大量插入 Java
在Java中向数据库执行大量插入操作,通常需要考虑性能和效率.对于大量数据的插入,有几种方法可以提高性能,比如使用批处理(Batch Insert).JDBC的批处理API.或者使用SQL Serve ...
- oeasy教您玩转python - 002 - # 你好世界 - 各位同学除夕快乐,除旧布新之时预祝能玩
你好世界 回忆上次内容 了解了 Python 安装了 Python 进入了 Python 退出了 Python 可是我们什么也没有做就离开了 IDLE 游乐场! 你好世界 #首先进入Python3 ...
- JavaWeb编写登录注册案例并把数据插入MySQL数据库中
小白学习了这么久的java,第一次上手编写一个完整的登录以及注册案例,麻雀虽小五脏俱全!!!! 案例: 登录和注册 第一:所需创建的包以及相关类 1,domain包(也就是平时所说的Javabean) ...
- Python 在PDF中添加、替换、或删除图片
PDF文件中的图片可以丰富文档内容,提升用户的阅读体验.除了在PDF中添加图片外,有时也需要替换或删除其中的图片,以改进视觉效果或更新信息.本文将提供以下三个示例,介绍如何使用Python 操作PDF ...
- 【SpringCloud】 Re02 Nacos
运行Nacos注册中心 win版Nacos在bin目录下打开cmd 执行此命令以运行单机模式的Nacos startup.cmd -m standalone 控制台输出: Microsoft Wind ...
- Ubuntu18.04 系统环境下 vscode中忽略pylint某些错误或警告
相关: ubuntu18.04系统环境下使用vs code安装pylint检查python的代码错误 ====================================== 假设已经在前文(ht ...
- 破局SAP实施难题、降低开发难度,定制化需求怎样快速上线?
前言 SAP 是全球领先的业务流程管理软件供应商之一,其提供广泛的模块化解决方案和套件,所开发的软件解决方案面向各种规模的企业,帮助客户规划和设计业务流程.分析并高效设计整个价值链,以更好的了解和响应 ...
- 使用 Apache SeaTunnel 实现 Kafka Source 解析复杂Json 案例
版本说明: SeaTunnel:apache-seatunnel-2.3.2-SNAPHOT 引擎说明: Flink:1.16.2 Zeta:官方自带 前言 近些时间,我们正好接手一个数据集成项目,数 ...
- 023.Ubuntu常见个性化配置
root登录设置 ubuntu默认关闭了root账户,可根据实际情况开启或关闭root登录. ubuntu@localhost:~$ sudo apt install openssh-server u ...
- quartz监控日志(一)
最近几个月,现网总是出现定时器不执行的情况,或者定时器卡死的情况,而又不方便排查,只能依靠quartz的debug日志以及错误日志来监控定时器的执行情况,并且随着我们系统中job越来越多,而使得job ...