1
votes

I need the generated nuxt application send requests to '/'. Thus, the api of the application will be in the same place where its static generated files are located.

I faced with problem: when running 'nuxt generate' process.server is true and process.browser is false. During generating, nuxt send queries to server baseURL (localhost:3000), it's ok. But generated javascript code also trying send queries to localhost:3000.

I run command

 http-server -c-1 -p 3001 ./dist/

and open localhost:3001 in browser, I see generated page, and error in console:

 Failed to load http://localhost:3000/data/pages.db

In my nuxt.config.js

  axios: {
    browserBaseURL: '/',
  },

When I run npm run dev in browser all right, browser send requests to '/', but generated app still send requests to localhost:3000

How I can resolve this issue?

UPD: I need get json files from /static in asyncData. I think, I found solution.

I use axios, not @nuxtjs/axios and do following in one place:

 axios.defaults.baseURL = typeof window === 'undefined' 
     ? 'http://localhost:3000' : window.location.origin 

and after that in any component

 import axios from 'axios'

in asyncData:

 axios.get(`/data/teasers/${path}`)

In result, I can generate static files, place it to any domain, and js code can corrrectly get files from /static

I hope this will come in handy.

1

1 Answers

0
votes

A late response, that might be useful for other people.

If you wish to keep the code of your Nuxt application simple, you can use the @nuxtjs/axios module, and use a plugin to specify the baseUrl used from the browser.

yarn install '@nuxtjs/axios'

In nuxt.config.js:

  modules: [
    '@nuxtjs/axios'
  ],
  plugins: [
    '~/plugins/axios-set-client-baseurl.js'
  ],

In plugins/axios-set-client-baseurl.js:

export default function ({ $axios }) {
  if (process.client) {
    $axios.setBaseURL(window.location.origin)
  }
}