方法一:live-serverlive-server是一个npm工具,可以在项目目录下启动一个node服务,然后进行预览直接在浏览器中,自动全球化监听实时更新。两种安装方式:全局安装npmilive-server-g本地安装npmilive-server--save-dev直接使用live-server先初始化项目下的npm:npminit-y;然后可以选择全局安装或者本地安装live-server,然后在package.json的scripts属性中添加如下代码:"scripts":{"server":"live-server./--port=8181--host=localhost--proxy=/api:http://www.abc.com/api/"}包括代理设置代理。然后,当执行npmrunserver时,会自动打开当前项目,默认指向index.html页面。先在本地使用node安装live-server,执行如下命令:npmilive-server--save-dev然后在项目下新建build.js,代码如下:varliveServer=require("live-server");varparams={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":"nodebuild.js"}最后执行npmrundev本地静态页面启动,路径为:http://localhost:8081/详细参考地址:https://www.npmjs.com/package/live-server方法二:http-server全局安装http-servernpmi-ghttp-server用法:http-server[路径][选项]]其中的路径默认指向项目路径下的./public。如果不存在,请使用./。options是常用的配置,比如端口、代理地址等。常用配置:-p或--port要使用的端口(默认为8080)。它还将从process.env.PORT中读取。(setport)-aAddresstouse(defaultsto0.0.0.0)(setaccessaddress)-P或--proxy代理所有不能在本地解析到给定url的请求。例如:-Phttp://someurl.com(设置代理地址)-o[路径]启动服务器后打开浏览器窗口。(可选)提供要打开的URL路径。例如:-o/other/dir/(默认打开浏览器)cmd进入静态目录项目,可以进行如下操作:http-server./-o--port8085--proxyhttp://192.168.11.120:8888/当然这个命令也可以简写为:hs./-o-p8085-Phttp://192.168.11.120:8888/我们也可以初始化package.json,执行npminit-y,然后在package.json的scripts字段中添加以下代码:"scripts":{"dev":"http-server./-o--port8089--proxyhttp://192.168.11.120:8888/"}最后执行npmrundev,同样如此。使用http-server的主要缺点是浏览器不能自动刷新。官网github地址:https://github.com/http-party/http-server方法三:Express搭建使用express搭建简单搭建使用express搭建前端静态页面环境,新建build文件夹下项目,并创建dev.js(开发环境启动文件)和index.js(配置文件,如端口)。我们只需要安装express和http-proxy-middleware,如下:npmiexpresshttp-proxy-middleware-Dindex.jscode:module.exports={port:8081,host:'localhost',proxyTable:[{api:'/api',target:'http://192.168.1.112:8081/'}]}dev.js代码如下:constexpress=require('express');const{createProxyMiddleware}=require('http-proxy-middleware');const{port=8080,proxyTable=[]}=require('./index.js');constapp=express();app.use('/',express.static('./'));//设置静态资源访问路径proxyTable.forEach((item)=>app.use(createProxyMiddleware(item.api,{target:item.target,//目标服务器主机changeOrigin:true,////默认false,do需要把原来的hostheader改成目标URLws:true//是否代理websockets})))app.listen(port,()=>{console.log(`listen:${port}`);})在package.json中配置启动快捷键,如下:"scripts":{"dev":"nodeconfig/dev.js"}运行npmrundev启动本地服务器,在本地运行localhost:8081(default运行项目下的静态文件index.html),其他静态页面如需添加相应路径。其中http-proxy-middleware其实就是对http-proxy进行了封装,使用起来更加方便简单。旧版http-proxy-middleware参考:http-proxy-middleware使用方法及实现原理(源码解读),其中新版http-proxy-middleware的使用方法参考github使用browser-sync实现热更新优化代码如下:constexpress=require('express');constpath=require('路径');consttimeout=require('connect-timeout');const{createProxyMiddleware}=require('http-proxy-middleware');const{port=8080,proxyTable=[],host='localhost'}=require('./index.js');constapp=express();constpathname=path.resolve(__dirname,'../');constbs=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,//目标服务器主机changeOrigin:true,////默认false,do你需要改变原始主机头是目标URLws:true//是否代理websockets})))app.listen(port,()=>{bs.init({//启动一个Browsersyncproxyproxy:`http://${host}:${port}`,notify:true,//notifyport:8085,//files:['**']//文件必须包含,不包含网上修改的文件不会刷新;可以指定文件类型、文件等文件:[`${pathname}/resources/**/*.html`,`${pathname}/index.html`,`${pathname}/public/**/*.js`,`${pathname}/public/**/*.css`]})})当然也可以使用watch方法监听文件变化。更改代码如下:constexpress=require('express');constpath=require('路径');consttimeout=require('connect-timeout');const{createProxyMiddleware}=require('http-proxy-middleware');const{port=8080,hotUpdate=false,proxyTable=[],host='localhost'}=require('./index.js');constapp=express();constpathname=path.resolve(__dirname,'../');constbs=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,{ttarget:item.target,//目标服务器主机changeOrigin:true,////默认false,是否将原始主机头更改为目标URLws: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({//启动浏览器同步代理proxy:`http://${host}:${port}`,notify:true,//通知端口:8085})})注:Browsersync允许浏览器实时快速响应文件变化并自动刷新。Browsersync文档方法4:使用node内置模块http启动服务consthttp=require('http');constfs=require('fs');constpath=require('路径');consthttpProxy=require('http-proxy');constchildProcess=require('child_process');//可以自动打开浏览器constfilepath=path.resolve(__dirname,'./');常量代理y=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('
404错误
您访问的页面/内容不存在
');res.end();}else{res.write(data);res.end();}}})})}).listen(8080,()=>{console.log('服务开始');});childProcess.exec('开始http://localhost:8080/index.html');然后在地址栏输入localhost:8080/index.html(我的index.html放在根路径下,根据具体路径填写)另一种方式:consthttp=require('http');constfs=require('fs');constpath=require('path');consthttpProxy=require('http-proxy');constchildProcess=require('child_process');//可以自动打开浏览器constfilepath=path.resolve(__dirname,'./');constproxy=httpProxy.createProxyServer();//创建代理服务器const{proxyTable=[]}=require('./config/index.js');constserver=newhttp.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('404错误
您访问的页面/内容不存在
');重发();}else{res.write(数据);水库结尾();}}})})})server.listen(8080,()=>{console.log('服务启动');});childProcess.exec('starthttp://localhost:8080/index.html');方法五:Nginx配置conf主要配置代码:http{#nginx负载均衡配置upstreamdynamic_balance{#ip_hash;服务器192.168.100.123:8081;}#省略其他服务器{listen80;服务器名称本地主机;#访问项目路径根网站;indexindex.htmlindex.htm;#将原http请求的Header中的Host字段转发给转发请求proxy_set_headerHost$host;#获取用户真实IPproxy_set_headerX-real-ip$remote_addr;proxy_set_headerX-转发-对于$proxy_add_x_forwarded_for;#接口转发位置/base/{proxy_passhttp://dynamic_balanCE;}#启用历史模式(任何请求只返回index.html)location/{try_files$uri$uri//index.html;}}}参考live-server官网http-server官网LiveNode.js解决前端跨域问题LiveNode-github