http-proxy-middleware插件解决跨域、鉴权、图片防盗链

普及一下这个插件的一些使用方法,只讲解一些常用,但有些生涩的地方,具体的还是得看官方文档

先说说这个插件是干嘛的吧。

The one-liner node.js http-proxy middleware for connect, express and browser-sync

Node.js proxying made simple. Configure proxy middleware with ease for connect, express, browser-sync and many more.

Powered by the popular Nodejitsu http-proxy.

我的理解,就是一个中间件,是http-proxy的封装,能给express,connect browser-sync等使用。

最常用在什么地方?

用来跨域的,例如跟webpack-dev-server配合使用是现在最流行的吧,vue react等一些脚手架工具中也已经集成了,所以你配置几行代码,就能跨域了。

proxyTable: {
    '/api': {
        target: 'http://localhost:3000',// 后端真实接口地址
        changeOrigin: true,
    }
},
复制代码

发出去的正常请求呢就是

'http://localhost:8000/api/users/info'
复制代码

pathRewrite的作用

但是,我们知道,公司内部的很多接口,不是api开头的,直接users,classify,top等开头,不可能写很多匹配规则吧,那怎么办,pathRewrite可以随意修改路径,匹配api,然后变成空。

proxyTable: {
    '/api': {
            target: 'http://localhost:3000', // 后端真实接口地址
            changeOrigin: true,
            pathRewrite: {
           '^/api': '/api' //重写,
        }
    }
},
复制代码

真实请求接口。

"http://localhost:3000/users/info"
复制代码

router的作用

可以理解就是重写target,但是注意的是,但使用时一定要带上http://的一个完整url地址

使用

axios.get('http://localhost:3000/rest/books/123') -> http://localhost:3000/rest/books/123 //携带http头
复制代码

配置

const routers = {
    '/rest': 'http://localhost:30001' 
};
const proxyTable = {
  '/api': {
    target: 'http://localhost:3000',
    changeOrigin: true,
    logLevel: 'debug',
    pathRewrite: {
      '^/api': ''
    },
    router: routers
  }
};
复制代码

为什么我推荐用携带http://开头的完整路径呢,因为当发送出去的请求地址,同时匹配'/api' '/rest'的时候,其实也会去rest的那个服务器地址下,容易混淆,下面请看。

鉴权

如果只想简单的验证接口是否需要token,或者我们在用一些收费接口的时候,总需要携带一些token,可以这么做。

proxy: {
    '/api': {
        target: 'http://localhost:3000',
        changeOrigin: true,
        pathRewrite: {
            '^/api': ''
        },
        headers: {
            token: 'token'
        }
    }
复制代码

referer防盗链

有时候一些引用第三方的图片会破图的现象,可以用这种办法。

proxy: {
    '/api': {
        target: 'http://localhost:3000',
        changeOrigin: true,
        pathRewrite: {
            '^/api': ''
        },
        headers: {
            referer: '' //
        }
    }
复制代码

onProxyRes(cookie跨域的场景)

还有一个业务场景就是,当我们本地调试测试或者线上代码的时候,会因为后端cookie设置了一些安全策略,而导致本地开发环境cookie丢失。这是因为由于同源策略的限制,所读取的cookie为跨域请求接口所在域的cookie,而非当前页。如果想实现当前页cookie的写入,则用以下办法。

虽然官方文档有说可以用cookieDomainRewrite 和cookiePathRewrite来搭配,但是曾经看到一种挺好的办法。

proxy: {
    '/api': {
        target: 'http://localhost:3000',
        changeOrigin: true,
        pathRewrite: {
            '^/api': ''
        },
        headers: {
            referer: '' //
        },
        onProxyRes(proxyRes) {
            const key = 'set-cookie';
            if (proxyRes.headers[key]) {
                const cookies = proxyRes.headers[key].join('').split(' ');
                // 切割掉一些严格的安全校验,只保留了第一项和Path,这样secure、domain都被忽略了。
                proxyRes.headers[key] = [cookies[0], 'Path=/'].join(' ');
            }
        }
    }

复制代码

值得一提的是,axios等ajax库,得配置withCredentials

websocket

加多一个就好 ws: true

额外的

在一些spa + node.js + 后端架构的项目里,或者一些ssr项目上,这个插件也可以在express中使用,如果你自己不想写代理服务器的话。


var express = require('express')
var proxy = require('../../index') // require('http-proxy-middleware');


var option = proxy({
  target: 'www.xxx.com',
  changeOrigin: true,
  logLevel: 'debug'
})

var app = express()

app.use('/api', option)

app.listen(3000)

复制代码

更多

点击查看

参考

基本用法

demo

猜你喜欢

转载自juejin.im/post/5c7d380e6fb9a049ec6bceed