Node.js 搭建当地HTTP服务器并运用node-http-proxy处理ajax跨域题目

原由:公司的产物替换前端框架,接口的接见原本是经由过程nginx设置反向代办完成的,当地没有装置nginx,就用node.js做一个。

设置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';
    原文作者:凉风小幸
    原文地址: https://segmentfault.com/a/1190000005101903
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞