关于node.js: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.jsonscripts下增加如下代码:

"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;
        }
    }
}

参考

  • live-server官网
  • http-server官网
  • LiveNode.js 解决前端跨域问题
  • LiveNode-github

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理