http-proxy-middleware及express实现反向代理

$ npm install --save-dev http-proxy-middleware

npm install express
// 引用依赖
var express = require('express');
var proxy = require('http-proxy-middleware');

// proxy 中间件的选择项
var options = {
        target: 'http://www.example.org', // 目标服务器 host
        changeOrigin: true,               // 默认false,是否需要改变原始主机头为目标URL
        ws: true,                         // 是否代理websockets
        pathRewrite: {
            '^/api/old-path' : '/api/new-path',     // 重写请求,比如我们源访问的是api/old-path,那么请求会被解析为/api/new-path
            '^/api/remove/path' : '/path'           // 同上
        },
        router: {
            // 如果请求主机 == 'dev.localhost:3000',
            // 重写目标服务器 'http://www.example.org' 为 'http://localhost:8000'
            'dev.localhost:3000' : 'http://localhost:8000'
        }
    };

// 创建代理
var exampleProxy = proxy(options);

// 使用代理
var app = express();
    app.use('/api', exampleProxy);
    app.listen(3000);

https://www.cnblogs.com/resultwp/p/9945606.htm vue 非常规跨域实现 proxyTable 设置及依赖 

1、config/index.js  设置跨域的地址
     proxyTable: {
        '/api': {    //跨域标识     请求地址为‘http://1xxx.xxx.com/index/list’, 请求时 “/api/index/list”
             target: 'http://1xxx.xxx.com',
             changeOrigin: true,   //允许跨域
             pathRewrite: {            //重新跨域标识
                  '^/api': ''
             }
         }
     },
 
2、build/webpack.dev.conf.js  引入express、http-proxy-middleware,如下:
    const proxyMiddleware = require('http-proxy-middleware')
 
    var express = require('express')
    var app = express()
    // proxy api requests
    const proxyTable=config.dev.proxyTable;
     Object.keys(proxyTable).forEach(function (context) {
      var options = proxyTable[context]
       if (typeof options === 'string') {
         options = { target: options }
       }
       app.use(proxyMiddleware(options.filter || context, options))
    })
a、引入express
  const express = require('express')
  const app = express()
b、引入反向代理插件 http-proxy-middlewar
  const proxyMiddlewar = require('http-proxy-middlewar')
 

代理配置

ok,这两个就是进行反向代理的准备工作。下面开始进行反向代理配置。首先,需要知道的是后端服务器的ip和端口号,
  const proxyPath = 'http://168.96.0.1:8080'   // 注意,这里只需要IP和端口号就可以了。这个ip我瞎写的
然后,将这个path配置到代理配置项中
  const proxyOption = {target: proxyPath,changeOrigin: true}

现在用express使用这个代理就好了

app.use('/api', proxyMiddlewar(proxyOption))  // 下面详细说明这一段  
app.listen() //表示监听的端口号也就是本地的端口号。用vue-cli构建的项目不需要写这行代码


express指定返回的拦截器处理:

const express = require("express");
const http = require("http");
const app = express();
////////////////////// 添加Log4js配置 /////////////////////////////
log.use(app);

////////////////////// 获取post过来的数据 /////////////////////////////
var bodyParser = require("body-parser");
app.use(bodyParser.urlencoded({ extended: false }));

////////////////////// 设置web工程的根目录 /////////////////////////////
app.use(express.static(__dirname + '/'));

////////////////////// 允许跨域 /////////////////////////////
app.all('*', function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Content-Type,Content-Length, Authorization, Accept,X-Requested-With");
    res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
    res.header("X-Powered-By",' 3.2.1')
    if(req.method=="OPTIONS") res.send(200);/*让options请求快速返回*/
    else  next();
});

////////////////////// 利用文件来拆分路由的规模 /////////////////////////////
var apiRouterIndex =  require('./routes/api/apiRouterIndex');
app.use('/api', apiRouterIndex);

////////////////////// 404处理 /////////////////////////////
app.get('*', function (req, res){
    console.log('404 handler..')
    res.render('common_page/404.html', {
        status: 404,
        title: 'NodeBlog',
    });
});

const server = http.createServer(app).listen(3000,'localhost',function () {
    const host = server.address().address;
    const port = server.address().port;
    // console.log("应用实例,访问地址为 http://%s:%s", host, port);
    process.env.host = host;
    // process 不能存储JSON格式的数据
    process.env.port = port;
    global.userInfo = {
        name: 'huangbiao',
        age: 30
    }
    app.SERVER_INFO = {
        name: 'zhangsan',
        age: 30
    }
});

需要使用app.use('/api', apiRouterIndex);这种方式配置URL请求的范围

const express = require('express');
const router = express.Router();
const tokenConfig = require('../common/config/tokenConfig');
// 处理token 的同一工具
const jwtUtils = require('../common/util/jwtUtils');
const apiService = require('./service/apiService.js');
var jwt= require('jsonwebtoken'); // 使用jwt签名
var fs = require('fs');

// 用来验证token,作为后台管理的拦截器
router.use(function (req, response, next) {
    var isToken = jwtUtils.checkTokenByRequest(req);
    // 如果获取的token 不合格,则给出提示信息
    if (!isToken) {
        response.status(200).json({
            state: 0,
            message: 'token数据不正确'
        });
        return false;
    }
    next();
});
// 查询所有的标签 接口
router.get('/tags/list', function(req, res, next) {
    // 创建tag标签
    apiService.queryTagList({},function (err, results, fields) {
        res.json({
            data: results
        });
    });
});

// 删除标签 接口
router.post('/tags/delete', function(req, res, next) {
    console.log(req.body);
    var id = req.body.id;
    // 删除tag标签
    apiService.deleteTagById(id, function (err, result) {
        res.json({
            status: true
        });
    });
});
module.exports = router;

在所有URL前面添加一个router.use(function (req, response, next) {next();});方法,用来验证token是否正确,这个拦截器只是针对http://localhost:3000/api打头的请求

// 引入模块依赖
const fs = require('fs');
const path = require('path');
const jwt = require('jsonwebtoken');
// 创建 token 类
class Jwt {
    constructor(data) {
        this.data = data;
    }
    // 检查token
    static checkTokenByRequest (requestObj) {
        // 拿取token 数据 按照自己传递方式写
        var tokenOrigin = requestObj.headers['Authorization'] || requestObj.headers['authorization'];
        if (tokenOrigin === '' || tokenOrigin === undefined || tokenOrigin === null ) {
            console.log('的值不能为空')
            return false;
        }
        // 获取服务器返回的token值
        var tokenStr = tokenOrigin.split(' ')[1];
        if (tokenStr === '' || tokenStr === undefined || tokenStr === null ) {
            console.log('token 格式不正确')
            return false;
        }
        return tokenStr;
    }
    // 从header请求中获取token 
    static getTokenFromHeader (requestObj) {
        var tokenStr = this.checkTokenByRequest(requestObj);
        if (tokenStr) {
            return tokenStr;
        } else {
            return null;
        }
    }
}

module.exports = Jwt;



https://www.jianshu.com/p/a248b146c55a http-proxy-middleware

https://blog.csdn.net/xmloveth/article/details/56847456 npm模块之http-proxy-middleware使用教程(译

https://www.jianshu.com/p/47c9e65f5a04 Vue项目中使用express实现反向代理

https://blog.csdn.net/hbiao68/article/details/85769755 express指定返回的拦截器处理

https://www.jianshu.com/p/9401a099c032?utm_source=oschina-app node.js之express模块

原文地址:https://www.cnblogs.com/shy1766IT/p/11087644.html