美文网首页
Node新建https服务并实现接口代理

Node新建https服务并实现接口代理

作者: hao102 | 来源:发表于2021-11-27 15:54 被阅读0次

    安装openssl生成本地秘钥和证书

    下载openssl客户端

    openssl下载地址
    下载安装后记住安装路径:复制到环境变量Path

    image.png
    以管理员身份代开CMD命令行模式;输入Openssl回车;确认是否安装成功(不报错)

    使用openssl生成秘钥

    1. 在秘钥生成的文件夹里打开cmd
    2. 执行命令openssl genrsa -out privatekey.pem 1024
      3.执行命令openssl req -new -key privatekey.pem -out certrequest.csr
      4.执行命令openssl x509 -req -in certrequest.csr -signkey privatekey.pem -out certificate.pem
      执行完后生成三个秘钥文件;将文件复制到项目目录

    配置https服务代码

    配置启动服务start.js

    const https = require('https');
    const url = require('url');
    const fs = require('fs');
    const start = (route, handler) => {
        function onRequest(request, response) {
            //使用cors解决跨域问题
            response.setHeader('Access-Control-Allow-Origin', '*');    //可设置允许跨域地址
            response.setHeader("Access-Control-Allow-Headers", "X-Requested-With,X_Requested_With,Content-Type");    // 允许post请求
            response.setHeader("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
            response.setHeader("Content-Type", "application/json;charset=utf-8");
    
            const parseUrl = url.parse(request.url);
            console.log(parseUrl, request.method);
    // 获取路径中第一段字母作为路由函数区分
            const pathFirstStr = parseUrl.pathname.match(/^\/[a-z]+/)[0];
    
            route(handler, pathFirstStr, request, response);
        }
        const options = {
            key: fs.readFileSync('../privatekey.pem'), //密钥路径
            cert: fs.readFileSync('../certificate.pem')
        };
        https.createServer(options, onRequest).listen(8888);
        console.log('serve has start https://127.0.0.1:8888')
    }
    exports.start = start;
    

    设置路由区分route.js

     
    function route(handler, pathname, request, response) {
        console.log(handler, pathname)
        if (typeof handler[pathname] === 'function') {
            handler[pathname](request, response);
        } else {
            console.log("No request handler found for " + pathname);
            response.writeHead(404, { "Content-Type": "text/html" });
            response.write("404 Not found");
            response.end();
        }
    }
    exports.route = route;
    

    设置逻辑处理代码requestHandler.js

    const https = require('https');
    const url = require('url');
    
    function proxyInterface(request, response) {
    // 服务器代理路径
        const targetUrl = 'https://xxx.xxx.xxx'
    
        const pathname = url.parse(request.url).pathname;
        const targetArr = targetUrl.split('//');
    
        const proxyOptions = {
            protocol: targetArr[0],
            host: targetArr[1],
            method: request.method,
            path: pathname,
            json: true,
            headers: {
                ...request.headers
            }
    
        }
    
        const proxyRequest = https.request(proxyOptions, function (proxyResponse) {
            console.log(proxyOptions);
            proxyResponse.on('data', function (chunk) {
                response.write(chunk, 'binary');
            })
            proxyResponse.on('end', function () {
                response.end()
            })
            proxyResponse.on('error',function(error){
                console.log(error)
            })
            response.writeHead(proxyResponse.statusCode, proxyResponse.headers);
        });
        // 本地接口数据传输,通知代理接口请求
        request.on('data', function (chunk) {
            
            proxyRequest.write(chunk, 'binary');
        });
    
        // 本地请求结束,通知代理接口请求结束
        request.on('end', function () {
            proxyRequest.end();
        });
    }
    
    exports.proxyInterface = proxyInterface;
    

    主函数并实现逻辑hand挂载index.js

    const serve = require('./start');
    const requestHanders = require('./requestHandler');
    const route = require('./route').route;
    const handle = {};
    // handle['/api']中/api就是我们路径中截取的第一串字符串
    handle['/api'] = requestHanders.proxyInterface
    serve.start(route, handle);
    

    相关文章

      网友评论

          本文标题:Node新建https服务并实现接口代理

          本文链接:https://www.haomeiwen.com/subject/kuxqxrtx.html