1'use strict';
2
3var express = require('express');
4var router = express.Router();
5
6var proxy_filter = function (path, req) {
7 return path.match('^/docs') && ( req.method === 'GET' || req.method === 'POST' );
8};
9
10var proxy_options = {
11 target: 'http://localhost:8080',
12 pathRewrite: {
13 '^/docs' : '/java/rep/server1' // Host path & target path conversion
14 },
15 onError(err, req, res) {
16 res.writeHead(500, {
17 'Content-Type': 'text/plain'
18 });
19 res.end('Something went wrong. And we are reporting a custom error message.' + err);
20 },
21 onProxyReq(proxyReq, req, res) {
22 if ( req.method == "POST" && req.body ) {
23 // Add req.body logic here if needed....
24
25 // ....
26
27 // Remove body-parser body object from the request
28 if ( req.body ) delete req.body;
29
30 // Make any needed POST parameter changes
31 let body = new Object();
32
33 body.filename = 'reports/statistics/summary_2016.pdf';
34 body.routeid = 's003b012d002';
35 body.authid = 'bac02c1d-258a-4177-9da6-862580154960';
36
37 // URI encode JSON object
38 body = Object.keys( body ).map(function( key ) {
39 return encodeURIComponent( key ) + '=' + encodeURIComponent( body[ key ])
40 }).join('&');
41
42 // Update header
43 proxyReq.setHeader( 'content-type', 'application/x-www-form-urlencoded' );
44 proxyReq.setHeader( 'content-length', body.length );
45
46 // Write out body changes to the proxyReq stream
47 proxyReq.write( body );
48 proxyReq.end();
49 }
50 }
51};
52
53// Proxy configuration
54var proxy = require( 'http-proxy-middleware' )( proxy_filter, proxy_options );
55
56/* GET home page. */
57router.get('/', function(req, res, next) {
58 res.render('index', { title: 'Node.js Express Proxy Test' });
59});
60
61router.all('/document', proxy );
62
63module.exports = router;
1// TIPS AND TRICK CUSTOM PROXY IN WEBPACK DEV SERVER BY restuwahyu13
2//NOTE this method like using CRA in React
3
4// manual proxy before
5module.exports = {
6 devServer: {
7 open: true,
8 compress: true,
9 hot: true,
10 inline: true,
11 lazy: true,
12 contentBase: resolve(process.cwd(), 'build'),
13 port: process.env.PORT || 3000,
14 proxy: {
15 '/api/*', {
16 target: 'http://localhost:3001',
17 secure: false,
18 changeOrigin: true,
19 headers: {
20 'Access-Control-Allow-Origin': '*',
21 'Access-Control-Allow-Credentials': '*',
22 'Access-Control-Allow-Methods': '*'
23 }
24 }
25 }
26 liveReload: false
27 }
28}
29
30// custom proxy after
31module.exports = {
32 devServer: {
33 open: true,
34 compress: true,
35 hot: true,
36 inline: true,
37 watchContentBase: true,
38 contentBase: resolve(process.cwd(), 'build'),
39 historyApiFallback: true,
40 before: (app, server, compiler) => {
41 const fileExist = existsSync('./src/setupProxy.js')
42 if (fileExist) {
43 const pathProxy = resolve(process.cwd(), 'src/setupProxy')
44 return require(`${pathProxy}`)(app)
45 }
46 },
47 port: process.env.PORT || 3000,
48 liveReload: false
49 }
50}