Nuxt How to set baseURL in dev or production

别等时光非礼了梦想. 提交于 2019-12-08 04:05:36

问题


This seems like a simple Nuxt question, but I just can't figure it out.

When running "NPM run dev" I want to set the Axios baseURL to "localhost/api" and when running from the dist folder after "NPM run generate" I want the baseURL to be "/api".

Is there a simple solution?


回答1:


This is the way to do it:

let development = process.env.NODE_ENV !== 'production'

module.exports = {
  axios: {
    baseURL: development ? 'http://localhost:3001/api' : 'https://domain/api'
  },
  modules: [
    '@nuxtjs/axios'
  ],
}

As you can see, you should specify full URL of your backend, including domain (except SPA-only mode).

And don't forget to install @nuxtjs/axios as dependency to try the example.




回答2:


you can also set api from outside (eg package.json scripts) by env variable

my package.json fragment (there is additional complexity when browser uses different api url then server side rendering, still all is supported by Nuxt itself with variables API_URL_BROWSER and API_URL)

 "scripts": {
    "dev-prodapi": "API_URL=https://kairly.com/api nuxt",
    "dev": "API_URL=http://localhost:8000/api nuxt",
    "dev-spa-prodapi": "API_URL=https://kairly.com/api nuxt --spa",
    "dev-spa": "API_URL=http://localhost:8000/api nuxt --spa",
    "build": "API_URL_BROWSER=https://kairly.com/api API_URL=https://internal-apihost/api/ nuxt build --modern=server",
    "start": "API_URL_BROWSER=https://kairly.com/api API_URL=https://internal-apihost/api/ nuxt start --modern=server",

and using no axios section in nuxt config at all.



来源:https://stackoverflow.com/questions/54770792/nuxt-how-to-set-baseurl-in-dev-or-production

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!