文件结构
代码结构.png
app.js
/**
* 应用程序的入口文件,此服务是为了对内网服务进行代理,不把内网服务暴露给外网
* Created by chengzan
* 2020.5.25
*/
// 加载模块
const express = require('express')
// const request = require('request')
const httpProxy = require('http-proxy');
const config = require('./serve_config.js')
// 创建app应用
const app = new express()
// 新建一个代理 Proxy Server 对象
const proxy = httpProxy.createProxyServer({});
// 捕获异常
proxy.on('error', function (err, req, res) {
res.writeHead(500, {
'Content-Type': 'text/plain'
});
res.end('Something went wrong. And we are reporting a custom error message.');
});
// 配置接口代理
app.use('/api', function (req, res) {
try {
proxy.web(req, res, { target: config.proxyUrl });
} catch (e) {
console.log(e)
}
})
// 配置文件上传接口代理
app.use('/file', function (req, res) {
try {
proxy.web(req, res, { target: config.proxyUploadUrl });
} catch (e) {
console.log(e)
}
})
// 配置文件上传接口代理
app.use('/SHCSAM', function (req, res) {
try {
let Cookies = {};
if (req.headers.cookie != null) {
req.headers.cookie.split(';').forEach(l => {
var parts = l.split('=');
Cookies[parts[0].trim()] = (parts[1] || '').trim();
});
}
req.headers['accessToken'] = Cookies['accessToken']
req.url = req.url.split('&accessToken=')[0]
proxy.web(req, res, { target: config.SHCSAMUrl });
} catch (e) {
console.log(e)
}
})
// 配置文件上传接口代理
app.use('/HMS', function (req, res) {
try {
const Cookies = {};
if (req.headers.cookie != null) {
req.headers.cookie.split(';').forEach(l => {
var parts = l.split('=');
Cookies[parts[0].trim()] = (parts[1] || '').trim();
});
}
req.headers['accessToken'] = Cookies['accessToken']
req.url = req.url.split('&accessToken=')[0]
proxy.web(req, res, { target: config.HMSUrl });
} catch (e) {
console.log(e)
}
})
app.use(function (req, res, next) {
//TODO 中间件,每个请求都会经过
next();
});
app.use(function (err, req, res, next) {
//TODO 失败中间件,请求错误后都会经过
console.error(err.stack);
res.status(500).send('Something broke!');
next();
});
// 设置静态文件托管 当用户访问的url以/开始,直接返回__dirname+'/dist'下的文件
app.use('/', express.static(__dirname + '/public/dist'))
// 监听http请求
app.listen(config.port, '0.0.0.0', function () {
console.log(config.port + '服务器启动成功-----------------' + new Date().toLocaleString());
});
console.log('Server running ...')
serve_config.js
// 地址
module.exports = {
proxyUrl: 'http://dev2.unisiot.com:53804',
proxyUploadUrl: 'https://dev2filecenter.unisiot.com/putFile',
// SHCSAMUrl: 'https://devl.unisiot.com:8180/SHCSAM',
SHCSAMUrl: 'http://localhost:9080/SHCSAM',
// HMSUrl: 'https://devl.unisiot.com:6281/HMS',
HMSUrl: 'http://localhost:9090/HMS',
port: 8071
}
package.json配置
{
"name": "static-H5-page",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"dev": "nodemon app.js",
"start": "nodemon app.js",
"serve": "nodemon app.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"body-parser": "^1.18.2",
"express": "^4.16.3",
"http-proxy": "^1.18.1",
"http-proxy-middleware": "^1.0.3",
"nodemon": "^2.0.1",
"request": "^2.88.0",
"sortable.js": "^0.3.0"
}
}