Example 1: package json proxy
"proxy": "http://localhost:4000"
Example 2: http-proxy-middleware option.onProxyReq:
'use strict';
var express = require('express');
var router = express.Router();
var proxy_filter = function (path, req) {
return path.match('^/docs') && ( req.method === 'GET' || req.method === 'POST' );
};
var proxy_options = {
target: 'http://localhost:8080',
pathRewrite: {
'^/docs' : '/java/rep/server1'
},
onError(err, req, res) {
res.writeHead(500, {
'Content-Type': 'text/plain'
});
res.end('Something went wrong. And we are reporting a custom error message.' + err);
},
onProxyReq(proxyReq, req, res) {
if ( req.method == "POST" && req.body ) {
if ( req.body ) delete req.body;
let body = new Object();
body.filename = 'reports/statistics/summary_2016.pdf';
body.routeid = 's003b012d002';
body.authid = 'bac02c1d-258a-4177-9da6-862580154960';
body = Object.keys( body ).map(function( key ) {
return encodeURIComponent( key ) + '=' + encodeURIComponent( body[ key ])
}).join('&');
proxyReq.setHeader( 'content-type', 'application/x-www-form-urlencoded' );
proxyReq.setHeader( 'content-length', body.length );
proxyReq.write( body );
proxyReq.end();
}
}
};
var proxy = require( 'http-proxy-middleware' )( proxy_filter, proxy_options );
router.get('/', function(req, res, next) {
res.render('index', { title: 'Node.js Express Proxy Test' });
});
router.all('/document', proxy );
module.exports = router;
Example 3: http proxy middleware
module.exports = {
devServer: {
open: true,
compress: true,
hot: true,
inline: true,
lazy: true,
contentBase: resolve(process.cwd(), 'build'),
port: process.env.PORT || 3000,
proxy: {
'/api/*', {
target: 'http://localhost:3001',
secure: false,
changeOrigin: true,
headers: {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Credentials': '*',
'Access-Control-Allow-Methods': '*'
}
}
}
liveReload: false
}
}
module.exports = {
devServer: {
open: true,
compress: true,
hot: true,
inline: true,
watchContentBase: true,
contentBase: resolve(process.cwd(), 'build'),
historyApiFallback: true,
before: (app, server, compiler) => {
const fileExist = existsSync('./src/setupProxy.js')
if (fileExist) {
const pathProxy = resolve(process.cwd(), 'src/setupProxy')
return require(`${pathProxy}`)(app)
}
},
port: process.env.PORT || 3000,
liveReload: false
}
}