接下来,JS环境变量在我的本地系统中不起作用

anauzrmj  于 2022-10-21  发布在  其他
关注(0)|答案(3)|浏览(208)

我对Next.js比较陌生,由于某些原因,在我的本地系统中,我不能访问环境变量。我在这里给出了所有相关的文件。
pages/index.js

import type {NextPage} from 'next'
import {useEffect} from "react";

const Home: NextPage = (props) => {

    useEffect(()=>{
        console.log("From Client API_URL:", process.env.API_URL)
        console.log("From Client NEXT_PUBLIC_API_URL:", process.env.NEXT_PUBLIC_API_URL)
    }, []);

    return (
        <>
            Hello World!
        </>
    )
}

export async function getServerSideProps() {
    console.log("From Client API_URL:", process.env.API_URL)
    console.log("From Client NEXT_PUBLIC_API_URL:", process.env.NEXT_PUBLIC_API_URL)
    return {
        props: {
            hello: "World!"
        }
    }
}

export default Home

.env.local文件

API_URL:https://fakestoreapi.com/
NEXT_PUBLIC_API_URL:https://fakestoreapi.com/

在浏览器中,我在控制台中获得了这个。

在服务器上,我收到了这个

> npm run dev

> dev
> next dev

ready - started server on 0.0.0.0:3000, url: http://localhost:3000
info  - Loaded env from C:\...\next-app\.env.local
warn  - SWC minify beta enabled. https://nextjs.org/docs/messages/swc-minify-enabled
event - compiled client and server successfully in 361 ms (217 modules)
wait  - compiling / (client and server)...
event - compiled client and server successfully in 92 ms (220 modules)
From server API_URL: undefined
From server NEXT_PUBLIC_API_URL: undefined
wait  - compiling /_error (client and server)...
event - compiled client and server successfully in 78 ms (221 modules)

下一个js版本:12.0.7
节点js版本:14.17.1
NPM版本:8.1.4

ohfgkhjo

ohfgkhjo1#

您的.env.local似乎没有正确配置,在使用=NOT为键赋值时应该这样做:

.env.local

API_URL=https://fakestoreapi.com/
NEXT_PUBLIC_API_URL=https://fakestoreapi.com/
pn9klfpd

pn9klfpd2#

如果希望能够在浏览器中访问环境变量,则需要在环境变量前面加上NEXT_PUBLIC_
如果没有这个前缀,您会发现您的环境变量不可用。
请查看此链接以了解有关此功能的更多信息。

f1tvaqid

f1tvaqid3#

不能在Next.js中访问客户端.env文件中的密钥,该文件不是以NEXT_PUBLIC_开头的。
此外,您的文件应为.env。

.env

NEXT_PUBLIC_API_URL:https://fakestoreapi.com/

Pages/index.js

import type {NextPage} from 'next'
import {useEffect} from "react";

const Home: NextPage = (props) => {

    useEffect(()=>{
        console.log("From Client API_URL:", process.env.NEXT_PUBLIC_API_URL)
        console.log("From Client NEXT_PUBLIC_API_URL:", process.env.NEXT_PUBLIC_API_URL)
    }, []);

    return (
        <>
            Hello World!
        </>
    )
}

export async function getServerSideProps() {
    console.log("From Client API_URL:", process.env.NEXT_PUBLIC_API_URL)
    console.log("From Client NEXT_PUBLIC_API_URL:", process.env.NEXT_PUBLIC_API_URL)
    return {
        props: {
            hello: "World!"
        }
    }
}

导出默认主页

相关问题