0

回顾下跨域解决方案http-proxy-middleware

 2 years ago
source link: https://www.daozhao.com/10524.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

回顾下跨域解决方案http-proxy-middleware

如果您发现本文排版有问题,可以先点击下面的链接切换至老版进行查看!!!

回顾下跨域解决方案http-proxy-middleware

我们在React(或Vue)项目本地开发过程中很容易由前端自己解决跨域问题,这里面就用到的是插件http-proxy-middleware,它并不是webpack独享的插件,而是一个通用插件,它对http-proxy进行了一层封装,更加方便我们使用。

之前刚接触webpack的时候写过一个webpack反向代理proxyTable设置

前几天有个测试同事找我解决她的跑的本地项目测试公司项目时,出现跨域的情况,因为前端项目不是spa项目,没有webpack之类的,所以就准备参照http-proxy-middleware来实现。

我们看看http-proxy-middleware的源码,目前它的最新版本是2.0.6,貌似2.x版本和1.x版本导出的方法有所不同

先看看npm官网的示例介绍

const express = require('express');
const { createProxyMiddleware } = require('http-proxy-middleware');

const app = express();

app.use('/api', createProxyMiddleware({ target: 'http://www.example.org', changeOrigin: true }));
app.listen(3000);

我们只是想在自己的express项目使用http-proxy-middleware,那就可以到此为止了,如果想继续了解http-proxy-middleware,我们就需要往下看这个createProxyMiddleware方法。

// node_modules/http-proxy-middleware/dist/index.js
const http_proxy_middleware_1 = require("./http-proxy-middleware");
function createProxyMiddleware(context, options) {
    const { middleware } = new http_proxy_middleware_1.HttpProxyMiddleware(context, options);
    return middleware;
}
exports.createProxyMiddleware = createProxyMiddleware;

继续看这个middleware是怎么实现的。

// node_modules/http-proxy-middleware/dist/http-proxy-middleware.js
const httpProxy = require("http-proxy");

class HttpProxyMiddleware {
    constructor(context, opts) {
        this.logger = (0, logger_1.getInstance)();
        this.wsInternalSubscribed = false;
        this.serverOnCloseSubscribed = false;
        // https://github.com/Microsoft/TypeScript/wiki/'this'-in-TypeScript#red-flags-for-this
        this.middleware = async (req, res, next) => {
            var _a, _b;
            if (this.shouldProxy(this.config.context, req)) {
                try {
                    const activeProxyOptions = await this.prepareProxyRequest(req);
                    this.proxy.web(req, res, activeProxyOptions);
                }
                catch (err) {
                    next(err);
                }
            }
            else {
                next();
            }
        })
        this.proxy = httpProxy.createProxyServer({});
        ...
}
exports.HttpProxyMiddleware = HttpProxyMiddleware;

终于找到核心实现middleware了,满足this.shouldProxy的就会利用this.proxy.web进行代理了,所以我们如果熟悉http-proxy的配置的,我们可以直接跳过http-proxy-middleware来使用http-proxy,但是好像也没这个必要吧。。。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK