• 在本地设置 http-proxy 代理 (前后端分离)


     1、 利用package.json 安装nodejs,创建package.json文件:内容如下

    "dependencies": {
      "http-proxy": "^1.16.2"
    }


    2、 当前目录下创建 index.js文件:内容如下
    var PORT = 3000;
    var projectPath = '/../project';  // 本地项目路径
    
    var http = require('http');
    var url=require('url');
    var fs=require('fs');
    var mine=require('./mine').types;
    var path=require('path');
    var httpProxy = require('http-proxy');
    
    var proxy = httpProxy.createProxyServer({
        target: 'http://192.168.12.220:8080/',   //接口地址
        // 下面的设置用于https
        // 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 (request, response) {
        var pathname = url.parse(request.url).pathname;
        //var realPath = path.join("main-pages", pathname); // 指定根目录
        console.log(pathname);
        var realPath = path.join("."+projectPath+'/', pathname);
        var ext = path.extname(realPath);
        ext = ext ? ext.slice(1) : 'unknown';
    
        //判断如果是接口访问,则通过proxy转发
        if(pathname.indexOf("/deviceService") > -1){
            proxy.web(request, response);
            return;
        }
    
        fs.exists(realPath, function (exists) {
            if (!exists) {
                response.writeHead(404, {
                    'Content-Type': 'text/plain'
                });
    
                response.write("This request URL " + pathname + " was not found on this server.");
                response.end();
            } else {
                fs.readFile(realPath, "binary", function (err, file) {
                    if (err) {
                        response.writeHead(500, {
                            'Content-Type': 'text/plain'
                        });
                        response.end(err);
                    } else {
                        var contentType = mine[ext] || "text/plain";
                        response.writeHead(200, {
                            'Content-Type': contentType
                        });
                        response.write(file, "binary");
                        response.end();
                    }
                });
            }
        });
    });
    server.listen(PORT);
    console.log("Server runing at port: " + PORT + ".");
    
    
    3、 如 index.js 第二行所配置:在当前目录上层目录创建项目文件夹 project
    放入index.html 测试页面
    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8" />
    <title>1111</title>
    <script>
    function readFile(a,back){
    setTimeout(function(){
    back(a);
    },1000);
    }
    
    const Thunk = function(fn) {
    return function (...args) {
    return function (callback) {
    return fn.call(this, ...args, callback);
    }
    };
    };
    var tf = Thunk(readFile);
    
    var gg = {
    *g(){
    var f1 = yield tf('fileA');
    console.log('---->>',f1);
    var f2 = yield tf('fileB');
    console.log('---->>',f2);
    // if (f2=="fileB")
    // return;
    // ...
    var fn = yield tf('fileN');
    console.log('---->>',fn);
    }
    }
    var g = function* () {
    var f1 = yield tf('fileA');
    console.log('---->>',f1);
    var f2 = yield tf('fileB');
    console.log('---->>',f2);
    // if (f2=="fileB")
    // return;
    // ...
    var fn = yield tf('fileN');
    console.log('---->>',fn);
    }
    
    const run_thunk = function (fn) {
    var gen = fn();
    
    function next(err, data) {
    var result = gen.next(err);
    if (result.done) return;
    result.value(next);
    }
    next();
    }
    
    function * a(){
    yield 1;
    yield 2;
    }
    
    var init = function(){
    // run_thunk(gg.g);
    var m = setTimeout(function(){
    alert('hell');
    },5000);
    
    setTimeout(function(){
    clearTimeout(m);
    alert('111');
    },1000);
    // var i = a();
    // console.log(i.next());
    // console.log(i.next());
    // console.log(i.next());
    }
    init();
    </script>
    </head>
    <body>
    1111
    </body>
    </html>

    4、cnpm install

    5、node index.js 开启3000服务

    6、注:mine.js 内容:

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

    项目结构:     -----  nodeServer

                                  |---- package.json

                                  |---- index.js

                                  |---- mine.js

                                  |---- node_modules

                          -----  project

                                  |---- index.html

  • 相关阅读:
    OpenCV进阶之路:神经网络识别车牌字符
    System.ComponentModel.DataAnnotations.Schema.TableAttribute 同时存在于EntityFramework.dll和System.ComponentModel.DataAnnotations.dll中
    windows server 禁用智能卡服务的步骤
    yum 安装时错误 Errno 14 Couldn't resolve host 解决办法
    解决 CentOS7 安装完成后ifconfig命令不能用
    C#下RSA算法的实现(适用于支付宝和易宝支付)
    centos下问题:connect:network is unreachable
    maven 跳过单元测试
    Docker
    Jenkins和Docker
  • 原文地址:https://www.cnblogs.com/Mvloveyouforever/p/7068073.html
Copyright © 2020-2023  润新知