Search code examples
proxynuxt.jsasyncdata

Nuxt: Proxy VS Async data VS Reload page


I am building a nuxt application and I am facing an issue with Proxy and Async data.

This is my nuxt.config (simplified)

modules: [
'@nuxtjs/axios',
'@nuxtjs/proxy'
],
axios: {
  proxy: true
},
proxy: {
  '/api': {
    target: 'http://www.example.com',
    pathRewrite: {
      '^/api': '/'
    }
  }
}

This is my asyncData code fragment (simplified):

async asyncData ({ store }) {
  await store.dispatch('fetchData')
}

Store action fetchData code (simplified):

async fetchData({ commit }) {
    const response = await myService.fetchData()
    commit('setData', response.data)
}

And at last, myService function (simplified):

fetchData () {
    return axios.get('/api/path-to-my-resource')
}

What is expected: To have the service triggering a call to the proxied endpoint, on both cases: visiting the page through a link or refreshing the page

What is happening: When I hit refresh on the page, instead of firing a call to the http://www.example.com/path-to-my-resource, I see that it tries to do it at /api/path/to-my-resource and of course it fails. From what I understand, when I refresh the page, the proxy is not working inside the asyncData hook.

I am pretty sure that there is something that I attempt wrongly, but I cannot find it. Can someone point me towards the right direction?


Solution

  • Try something like:

    proxy: {
      '/api/': { target: 'http://www.example.com', pathRewrite: {'^/api/': ''} }
    // ^^^^^                                                      ^^^^^^   ^^
    // Note the ending slashes.
    // And the rewrite rule.
    }
    

    That's how the docs are written: