This is a general introduction to the daily use of this plug-in, not to explain the very basic API, please accompany the official documentation to watch

Let’s start with what this plugin does.

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.

It is a middleware that encapsulates HTTP-Proxy and can be used for Express, Connect Browser-Sync, etc.

Where is it most commonly used?

Cross-domain applications such as Webpack-dev-server are the most popular, and vue React and other scaffolding tools are already integrated, so you can configure a few lines of code to cross domains.

proxyTable: {
    '/api': {
        target: 'http://localhost:3000',// Address of the real back-end interface changeOrigin:true,}},Copy the code

A normal request to make is

'http://localhost:3000/api/users/info'
Copy the code

The role of pathRewrite

As we know, many interfaces in the company do not start with API, direct users,classify,top, etc., and cannot write many matching rules. How to do that,pathRewrite can modify the path at will, match API, and then become empty.

proxyTable: {
    '/api': {
            target: 'http://localhost:3000', // Address of the real back-end interface changeOrigin:true,
            pathRewrite: {
           '^/api': ' '// override,}}},Copy the code

Real request interface.

"http://localhost:3000/users/info"
Copy the code

The function of the router

Overwrite target, but make sure you use http:// with a full URL

use

axios.get('http://localhost:3000/rest/books/123') - > HTTP: / / http://localhost:3000/rest/books/123 / / carry HTTP headersCopy the code

configuration

const routers = {
    '/rest': 'http://localhost:30001' 
};
const proxyTable = {
  '/api': {
    target: 'http://localhost:3000',
    changeOrigin: true.logLevel: 'debug',
    pathRewrite: {
      '^/api': ' '
    },
    router: routers
  }
};
Copy the code

The reason why I recommend using the full path starting with http:// is that when a request address is sent that matches both ‘/ API ‘and ‘/rest’, it will also go to the rest server address, which can be confusing, as shown below.

authentication

This can be done if you simply want to verify whether the interface requires a token, or if you always need to carry some token when using some paid interfaces.

proxy: {
    '/mmbiz_png': {
        target: 'https://mmbiz.qpic.cn',
        changeOrigin: true,

        headers: {
            token: 'token'}}Copy the code

Referer hotlinking prevention

Sometimes some reference to the third party pictures will break the phenomenon of the graph, can be used in this way.

The tricky part here is that instead of rendering a SRC online address directly with the IMG tag, we use ajax libraries such as Axios to request the image binary stream back, and then generate a URL via the URl.createObjecturl interface

axios
  .get(
    Then (({data}) => {var img = document.createElement(' ');img') var url = window.URL.createObjectURL(data) img.src = objectUrl img.onload = () => { window.URL.revokeObjectURL(url) }  document.body.appendChild(img) })Copy the code
proxy: {
    '/mmbiz_png': {
        target: 'https://mmbiz.qpic.cn',
        changeOrigin: true,
        headers: {
            referer: ' '// Select * from (); }}Copy the code

OnProxyRes (Cookie cross domain scenario)

Another business scenario is that when we debug the test or online code locally, the cookies of the local development environment cannot be written in because some security policies such as Secure Domain are set on the back-end cookies. This is because the cookie read is for the domain of the cross-domain request interface, not the current page, because of the same-origin policy restriction. If you want to write cookies to the current page, use the following method.

Although the official documentation states that cookieDomainRewrite and cookiePathRewrite can be used together, I have seen a good way to do this.

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(' '); // Cut off some strict security checks, only the first item and Path are retained, so that secure and domain are ignored. proxyRes.headers[key] = [cookies[0],'Path=/'].join(' '); }}}Copy the code

It is worth mentioning that ajax libraries such as AXIos need to be configured with withCredentials

websocket

Ws: true

additional

In some SPA + Node.js + back-end architecture projects, or some SSR projects, the plugin can also be used in Express if you don’t want to write a proxy server yourself.


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)

Copy the code

More and more

Click to view

reference

Basic usage

demo