起因:公司的产品更换前端框架,接口的访问原本是通过nginx配置反向代理实现的,本地没有安装nginx,就用node.js做一个。
node.js搭建本地http服务器参考了shawn.xie的《nodejs搭建本地http服务器》
node.js做转发使用node-http-proxy实现,官方文档:https://github.com/nodejitsu/node-http-proxy#using-https
配置http服务器和proxy转发
var http = require('http');
var httpProxy = require('http-proxy');
var fs = require('fs');
var mine = require('./mime').types;
var path = require('path');
var url = require('url');
var proxy = httpProxy.createProxyServer({
target: 'https://192.168.101.166:8088',//接口地址
ssl: {
key: fs.readFileSync('server_decrypt.key', 'utf8'),
cert: fs.readFileSync('server.crt', 'utf8')
},
secure: false
});
proxy.on('error', function(err, req, res){
res.writeHead(500, {
'content-type': 'text/plain'
});
console.log(err);
res.end('Something went wrong. And we are reporting a custom error message.');
});
var server = http.createServer(function(req, res){
var pathName = url.parse(req.url).pathname;
var realPath = req.url.substring(1);
var extName = realPath;
var indexOfQuestionMark = extName.indexOf('?');
if(indexOfQuestionMark >= 0){
extName = extName.substring(0, indexOfQuestionMark);
realPath = realPath.substring(0, indexOfQuestionMark);
}
extName = path.extname(extName);
extName = extName ? extName.slice(1) : 'unknown';
//判断如果是接口访问,则通过proxy转发
if(/\/svr\/.*$/.test(pathName)){
proxy.web(req, res);
return;
}
fs.exists(realPath, function(exists){
if(!exists){
res.writeHead(404, {'content-type': 'text/plain'});
res.write('The request URL:' + realPath + ' could not be found.');
res.end();
return;
}
fs.readFile(realPath, 'binary', function(err, file){
if(err){
res.writeHead(500, {'content-type': 'text/plain'});
res.end(err);
return;
}
var contentType = mine[extName] || 'text/plain';
res.writeHead(200, {'content-type': contentType});
res.write(file, 'binary');
res.end();
});
});
});
server.listen(8088);
mime.js
这里参考shawn.xie的源码,补充了几个字体文件的mime。
exports.types = {
"css": "text/css",
"gif": "image/gif",
"html": "text/html",
"ico": "image/x-icon",
"jpeg": "image/jpeg",
"jpg": "image/jpeg",
"js": "text/javascript",
"json": "application/json",
"pdf": "application/pdf",
"png": "image/png",
"svg": "image/svg+xml",
"swf": "application/x-shockwave-flash",
"tiff": "image/tiff",
"txt": "text/plain",
"wav": "audio/x-wav",
"wma": "audio/x-ms-wma",
"wmv": "video/x-ms-wmv",
"xml": "text/xml",
"woff": "application/x-woff",
"woff2": "application/x-woff2",
"tff": "application/x-font-truetype",
"otf": "application/x-font-opentype",
"eot": "application/vnd.ms-fontobject"
};
以上是全部的源码,配置中遇到几个问题说明如下:
1、接口采用https,所以http-proxy需要配置证书,按照官方的配置如下:
var proxy = httpProxy.createProxyServer({
target: 'https://192.168.101.166:8088',
ssl: {
key: fs.readFileSync('server_decrypt.key', 'utf8'),
cert: fs.readFileSync('server.crt', 'utf8')
},
secure: true
});
其中target是接口的IP地址,ssl配置key和证书,secure默认为true,运行访问接口后,node控制台提示:
{ [Error: unable to verify the first certificate] code: ‘UNABLE_TO_VERIFY_LEAF_SIGNATURE’ }
google后,这段意思大致是说证书未通过验证,通常在node中配置不验证证书即可。
rejectUnauthorized: false
但是我用的是http-proxy,没有rejectUnauthorized这个参数,再次阅读文档:
//
// Create the proxy server listening on port 443
//
httpProxy.createServer({
ssl: {
key: fs.readFileSync('valid-ssl-key.pem', 'utf8'),
cert: fs.readFileSync('valid-ssl-cert.pem', 'utf8')
},
target: 'https://localhost:9010',
secure: true // Depends on your needs, could be false.
}).listen(443);
其中secure这个参数的说明很模糊,尝试着将其设定为false,通过!
2、shawn.xie的源码中,对于url中扩展名的识别存在bug,比如这样的URL识别会取到最后一个点的位置,本来应该是woff2,结果却是0。http://localhost:8000/ab/resources/fonts/font.woff2?v=4.5.0
本来尝试用正则处理,但是后向引用在js不支持,就老老实实的用indexOf解决:
var realPath = req.url.substring(1);
var extName = realPath;
var indexOfQuestionMark = extName.indexOf('?');
if(indexOfQuestionMark >= 0){
extName = extName.substring(0, indexOfQuestionMark);
realPath = realPath.substring(0, indexOfQuestionMark);
//realPath是文件的真实路径,所以也要去掉扩展名后面?之后的部分
}
extName = path.extname(extName);
extName = extName ? extName.slice(1) : 'unknown';