How to setup a webpack dev server using both historyApiFallback and proxying remote api requests?

纵然是瞬间 提交于 2019-12-03 04:28:18

In Express middleware stack order matters.

Proxy should be set up at webpack config first than historyApiFallback, this is how it should look like:

  devServer:{
    contentBase: 'src/www',  //Relative directory for base of server
    devtool: 'eval',
    hot: true,        //Live-reload
    inline: true,
    port: 3000,        //Port Number
    host: 'localhost', //Change to '0.0.0.0' for external facing server
    proxy: {
      '^\/users|sitters|bookings': {
        target: 'http://127.0.0.1:3001',
        rewrite: function(req) {
          req.url = req.url.replace(/^\/api/, '');
        }
      }
    },
    historyApiFallback: true
  },

So of course proxy can be changed to any pattern or regex as an application needs it. In my case that's what I needed.

I end up with following solution:

const REMOTE_URL = process.env.REMOTE_URL || 'http://localhost:8090/';

const config = {
    output: {
        publicPath: '/'
    },
    devServer: {
        historyApiFallback: true,
        contentBase: './app',
        proxy: [{
            context: '/api',
            target: REMOTE_URL,
            pathRewrite: {
                '^/api' : '/'
            }
        }]
    }
};

So all request to http://locahost:port/api/ goes through proxy, and /api rewrited.

For example http.get('/api/users') go to just /users.

Btw. Object inside proxy is just http-proxy-middleware configuration.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!