【问题标题】:Nuxt How to set baseURL in dev or productionNuxt 如何在开发或生产环境中设置 baseURL
【发布时间】:2019-07-13 05:24:07
【问题描述】:

这似乎是一个简单的 Nuxt 问题,但我就是想不通。

当运行“NPM run dev”时,我想将 Axios baseURL 设置为“localhost/api”,当在“NPM run generate”之后从 dist 文件夹运行时,我希望 baseURL 为“/api”。

有简单的解决办法吗?

【问题讨论】:

    标签: vue.js axios nuxt.js


    【解决方案1】:

    这是通过nuxt.config.js实现的方法:

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

    如您所见,您应该指定后端的完整 URL,包括域(仅 SPA 模式除外)。

    并且不要忘记安装 @nuxtjs/axios 作为依赖项来尝试示例。

    【讨论】:

    • 工作完美!
    • @SteveO 酷。在这种情况下,您最好将此问题标记为已解决,只需说
    • 不工作的兄弟
    【解决方案2】:

    您也可以通过环境变量从外部(例如 package.json 脚本)设置 api

    我的 package.json 片段(当浏览器使用不同的 api url 然后服务器端渲染,仍然由 Nuxt 本身支持,变量 API_URL_BROWSER 和 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",
    

    并且在 nuxt 配置中根本不使用 axios 部分。

    【讨论】:

      猜你喜欢
      • 2015-04-04
      • 2021-09-10
      • 2023-03-17
      • 2020-01-21
      • 2012-04-05
      • 2017-12-20
      • 2015-12-07
      • 2011-08-06
      • 1970-01-01
      相关资源
      最近更新 更多