根据 Nuxt 3 中的环境使用 .env 中不同的 api url

问题描述 投票:0回答:1

我正在尝试对阶段(开发)和生产环境使用不同的 api url 我已经在 nuxt.config.js 中定义了这样的 url

import redirectSSL from "redirect-ssl";

const isProdEnv = process.env.NODE_ENV === "production";
const DEV_API_URL =  "https://example-stage.herokuapp.com/v1/";
const PROD_API_URL = "https://example.herokuapp.com/v1/";
const API_URL = isProdEnv ? PROD_API_URL : DEV_API_URL;

export default defineNuxtConfig({
  devtools: { enabled: true },
  ssr: true,
  /*
   ** Headers of the page
   */
  app: {
    head: {
      title: "project",
      meta: [
        {
          charset: "utf-8",
        },
        {
          name: "viewport",
          content: "width=device-width, initial-scale=1",
        },
        {
          "http-equiv": "X-UA-Compatible",
          content: "IE=edge",
        },
      ],
      link: [
        {
          href: "https://fonts.googleapis.com/css?family=Lato:400,700,900&display=swap",
          rel: "stylesheet",
        },
        {
          href: "https://fonts.googleapis.com/css?family=Montserrat:400,500,700&display=swap",
          rel: "stylesheet",
        },
        {
          href: "https://fonts.googleapis.com/css?family=Material+Icons|Material+Icons+Outlined|Material+Icons+Two+Tone|Material+Icons+Round|Material+Icons+Sharp",
          rel: "stylesheet",
        },
      ],
      script: [],
    },
  },
  vite: {
    css: {
      preprocessorOptions: {
        scss: {
          additionalData: '@import "@/assets/scss/index.scss";',
        },
      },
    },
  },
  css: ["bootstrap/dist/css/bootstrap.min.css", "flatpickr/dist/flatpickr.css"],
  runtimeConfig: {
    public: {
      apiURL: API_URL || "https://example.herokuapp.com/v1/",
    },
  },
  modules: [
    "@pinia/nuxt",
    // "floating-vue/nuxt"
  ],
  serverMiddleware: [
    redirectSSL.create({
      enabled: process.env.NODE_ENV === "production",
    }),
  ],

  build: {
    /*
     ** You can extend webpack config here
     */
    extend(config, ctx) {
      console.log(config);
      config.module.rules.push({
        test: /\.(csv|xlsx|xls)$/,
        loader: "file-loader",
        options: {
          name: `files/[name].[ext]`,
        },
      });
    },
  },
});

当我在本地运行它时,它工作正常,我使用

node .output/server/index.mjs
启动了本地生产服务器,并且它获取了 API URL,但是当我在 Heroku 中部署它时,它没有正确获取 API_URL 我已将 heroku 中的 NODE_ENV 设置为阶段的 satage构建,但它总是读取生产 URL,因为后备是运行时配置中的生产 URL,任何人都可以帮助我解决这个问题吗?

nuxt.js nuxtjs3
1个回答
0
投票

通过将.env文件中的变量名称更改为

 NUXT_PUBLIC_API_BASE
并将runtimeConfig更改为此

解决了该问题
runtimeConfig: {
    public: {
      apiBase:
        process.env.NUXT_PUBLIC_API_BASE
       
    },
  },

基于此处的文档https://nuxt.com/docs/guide/going-further/runtime-config#environment-variables

© www.soinside.com 2019 - 2024. All rights reserved.