Matt
Matt

Reputation: 10312

Vue, how do I proxy everything excluding a specific path?

I would like the webpack-dev-server (underneath Vue CLI) to proxy everything that doesn't begin with /app to http://127.0.0.1:8000, how can I achieve this?

For example:

I've tried this inside my vue.config.js:

module.exports = {
    configureWebpack: {
        devServer: {
            port: 8080,
            proxy: 'http://127.0.0.1:8000!/app/**',
        }
    }
}

Upvotes: 2

Views: 3917

Answers (4)

Matt
Matt

Reputation: 10312

I've solved this using vue-cli-plugin-proxy. After installing it, I added the following to my vue.config.js.

module.exports = {
    publicPath: '/app',

    pluginOptions: {
        proxy: {
            context: '!/app/**',
            options: {
                target: 'http://127.0.0.1:8000',
            }
        }
    },
}

Upvotes: 0

Mark
Mark

Reputation: 21

Alternatively, you can use Regex to match url excluding a prefix:

devServer: {
    port: 8080,
    proxy: {
        "^(?!/app)": {
            target: "http://127.0.0.1:8000",
            changeOrigin: true
        }
    }
}

Upvotes: 2

Matt
Matt

Reputation: 10312

As per Nafees's answer, the following code enables me to access /app/ and every other URL gets proxied. All except /, which doesn't get forwarded to the proxy.

module.exports = {
    publicPath: '/app/',

    configureWebpack: {
        devServer: {
            index: '',
            proxy: {
                '/': {
                    target: 'http://127.0.0.1:8000',
                    bypass: function(req, res, proxyOptions) {
                        if (req.url.startsWith('/app/')) {
                            return req.url;
                        }

                        return null;
                    }
                },
            },
        }
    }
}

Upvotes: 1

Nafees Anwar
Nafees Anwar

Reputation: 6598

You can do this by defining bypass function in your proxy settings like this.

devServer: {
    index: '', // specify to enable root proxying
    proxy: [{
        context: () => true,
        target: 'http://127.0.0.1:8000',
        bypass: (req) => {
          if (req.url.startsWith('/app')) {
            return req.url // do not proxy
          }
          return false
        }
    }],
}

Upvotes: 3

Related Questions