Hor*_*don 13 javascript environment-variables node.js digital-ocean next.js
我在 DigitalOcean 上部署了 Strapi 后端和 Next.js 前端应用程序。在 DigitalOcean 上为前端设置了一个环境变量:API_URL = ${APP_URL}/api
我获取此变量来生成基本 url:
// constants.js
export const BASE_URL =
process.env.NODE_ENV === "production"
? process.env.API_URL
: "http://localhost:1337";
Run Code Online (Sandbox Code Playgroud)
它似乎工作正常,应用程序也从本地主机和部署中的后端获取内容。当我尝试加载图像时,问题就出现了,该图像的路径应该是基本 url 和获取的相对路径的连接。我为此创建了一个 utilitz 函数:
// utilities.js
import { BASE_URL } from "./constants";
export const getImageURL = (relPath) => `${BASE_URL}${relPath}`;
Run Code Online (Sandbox Code Playgroud)
当我将此函数用于 html img 标签时,它会在开发环境和生产环境中加载:
<img src={getImageURL(homePage.Hero[0].Image.url)} />
但是,当我尝试在同一组件中为 div 设置背景时,基本 url 未定义,并且图像不会出现在部署的站点中(在本地主机上工作正常)。
我不知道为什么 url 生成对于代码的某些部分可以,而对于其他部分则不行。
部署的构建命令是:yarn build && next export -o _static
这是完整的组件:
import styles from "../styles/Home.module.css";
import { getImageURL } from "../lib/utilities";
import { useEffect } from "react";
import { BASE_URL } from "../lib/constants";
export default function Home({ homePage }) {
console.log(BASE_URL); // undefined
useEffect(() => {
if (window) {
console.log(BASE_URL); // undefined
document.getElementById("container").style.backgroundImage = `url('${getImageURL(homePage.Hero[0].Image.url)}')`; // url is undefined/realtivepath
}
});
return (
<div id="container">
<img src={getImageURL(homePage.Hero[0].Image.url)} />
</div>
);
}
export const getStaticProps = async () => {
const res = await fetch(`${BASE_URL}/home-page`); // OK for dev and deploy
const homePage = await res.json();
return {
props: {
homePage,
},
};
};
Run Code Online (Sandbox Code Playgroud)
fel*_*osh 20
默认情况下,出于安全考虑,Next.js不会向浏览器公开所有变量。process.env.X
为了向浏览器公开环境变量,它的NEXT_PUBLIC_名称中必须有前缀。
根据您的情况,重命名API_URL为NEXT_PUBLIC_API_URL并使用它。
欲了解更多信息:https ://nextjs.org/docs/basic-features/environment-variables
| 归档时间: |
|
| 查看次数: |
35748 次 |
| 最近记录: |