How to use webpack dev proxy with Nuxt

2019-07-26 06:46发布

问题:

Using Nuxt to develop a universal JS app, I'm attempting to configure webpack's dev proxy so that, in development only, requests to /api get proxied to http://127.0.0.1:500/api where they'll reach a Python REST API. Following the Nuxt docs, I've extended the webpack config in nuxt.config.js like so:

build: {
  extend (config, { isDev }) {
    // Proxy /api to Python only in dev
    if (isDev) {
      const devServer = {
        proxy: {
          '/api': 'http://127.0.0.1:5000'
        }
      }
      config.devServer = devServer;
    }
  }
}

If I log the config, I see that change being applied:

...
devServer: { proxy: { '/api': 'http://127.0.0.1:5000' } } }
...

Yet, when I visit http://127.0.0.1:8080/api/things, my Nuxt app is returned (it runs on port 8080 in dev), indicating that the webpack dev proxy is not catching the /api path and performing the proxying. Just to confirm that the proxy destination is working, if I visit http://127.0.0.1:5000/api/things, I get the expected API response. Why, when I've extended the Nuxt webpack config to enable the webpack dev proxy, does the proxy not function?

I have, however, had success with the @nuxt/proxy module, but critically, I could not find a way to make it only affect development and not production. That portion of nuxt.config.js looked like this:

axios: {
  proxy: true
},
proxy: {
  '/api': 'http://127.0.0.1:5000'
},

I'm happy to use the @nuxt/proxy module instead of (on top of?) the webpack dev proxy if it can be made to work in development only.

回答1:

Ugh, I'm barking up the wrong tree.

Nuxt needs to proxy, even in production. When my initial request is processed and the app is server-side-rendered, any API requests need to be proxied because the Node server is doing the calling, not a browser, so those API requests won't even hit my production router like nginx or HAProxy (which typically does my routing for / and /api to the appropriate services).