nuxt / http

Universal HTTP Module for Nuxt.js
https://http.nuxtjs.org
MIT License
229 stars 51 forks source link

Break fetch and asyncData hooks with relative paths #153

Closed frbuceta closed 3 years ago

frbuceta commented 3 years ago

Nuxt Http is breaking when used with relative paths in the asyncData and fetch hook, below I put some pieces of code.

export default {
  data() {
    return {
      httpData: [],
    }
  },
  async fetch() {
    this.httpData = await this.$http
      .$get('/accounts/users')
      .then((result) => {
        return result.map((o) => ({
          ...o,
          _text: `${o.firstName} ${o.lastName}`,
        }))
      })
  },
  mounted() {
    this.$nextTick(() => {
      this.$fetch()
    })
  },
}

Error in fetch(): Only absolute URLs are supported

atinux commented 3 years ago

It should work, do you mind creating a reproduction using https://template.nuxtjs.org please?

frbuceta commented 3 years ago

It should work, do you mind creating a reproduction using https://template.nuxtjs.org please?

yes, https://codesandbox.io/s/practical-proskuriakova-zrr9j?file=/pages/index.vue

atinux commented 3 years ago

Hi @frbuceta, actually the baseURL has to be an absolute url, otherwise during SSR it cannot know what url to fetch (and it is required), on browser it automatically adds the window.location.hostname.

You need to use the prefix option when using the proxy:

export default {
   http: {
    // See https://http.nuxtjs.org/api/#options
    prefix: "/api",
    proxy: true
  },

  proxy: {
    "/api": {
      target: "https://jsonplaceholder.typicode.com",
      pathRewrite: { "^/api": "" }
    }
  },
}