如何访问Nuxt 3中/server/api目录中的process.env变量?

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

在 Nuxt 3 应用程序中,我在 Nuxt 3 的

/api/
文件夹中创建了一个
server
文件夹,我在其中创建了一个文件
posts.ts
。在此文件中,我正在集成 Ghost CMS 内容 API。从那时起,我安装了该包并导入到
post.ts
文件中,并且我尝试通过
useRuntimeConfig() 
可组合项访问 ENV 变量。

这样做时我收到以下错误。怎么解决?

[nuxt] 需要访问 Nuxt 实例的可组合项在插件、Nuxt 挂钩、Nuxt 中间件或 Vue 设置函数之外调用。这可能是?> 不是 Nuxt 错误。如需了解更多信息,请访问

https://nuxt.com/docs/guide/concepts/auto-imports#vue-and-nuxt-composables
。 在 Module.useRuntimeConfig (D:\my-project\website 颂歌模块 uxt\dist pp uxt.js:193:27) 在 D:\my-project\website\server pi\posts.ts:5:54

参见下面的代码:

import GhostContentAPI from '@tryghost/content-api';

const { ghostUrl, ghostKey} = useRuntimeConfig();
export const api = new GhostContentAPI({
  url: ghostUrl,
  key: ghostKey,
  version: 'v5.0'
});

我已经尝试过另一种使用

process.env.GHOST_URL
的方法,但这也即将到来
undefined

import GhostContentAPI from '@tryghost/content-api';

export const api = new GhostContentAPI({
  url: process.env.GHOST_URL ?? '',
  key: process.env.GHOST_API_KEY ?? '',
  version: 'v5.0'
});
nuxt.js nuxtjs3 composable
1个回答
0
投票

你好,我发现最好的方法是使用 vite。

在 .env 文件中将变量定义为

VITE_GHOST_URL="your URL"

并在服务器文件夹中的 post.ts 文件中通过

const ghostUrl = 
${import.meta.env.VITE_GHOST_URL}
;
获取变量 并在 post.ts 文件中任何需要 URL 的地方使用 GhostUrl。

这是最好的方法,但只有当你的项目是使用 vite 设置时才有效。

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