NextJS:[点]env.localreturns未定义
NextJS: [dot]env.local returns undefined
在我的应用程序中,我在 .env.local 文件中创建了一个环境变量,并通过 process.env.ENV_KEY 将其提取到组件中。但它没有返回实际值,而是 returns 未定义值。
.env.local
API_ENDPOINT = "http://localhost:4200/api/"
在组件中我得到的值是 process.env.API_ENDPOINT
但它 returns 是 undefined
App.js
function App(props) {
const loginUser = async event => {
event.preventDefault()
axios.post(`${process.env.API_ENDPOINT}/login`, data)
.then((response) => {
router.push('/')
})
}
}
我也尝试过配置到 env.js 文件中,但也没有任何效果。
exports.env = {
API_ENDPOINT: process.env.API_ENDPOINT
}
And into component have imported as
import {env} from './config.js'
function App(props) {
const loginUser = async event => {
event.preventDefault()
axios.post(`${env.API_ENDPOINT}/login`, data)
.then((response) => {
router.push('/')
})
}
}
此外,我还尝试创建一个构建,然后 运行 项目,然后还尝试创建 returns undefined
值。
我查看的参考资料
- Nextjs env variable is always undefined
- https://nextjs.org/docs/basic-features/environment-variables#loading-environment-variables
By default all environment variables loaded through .env.local are
only available in the Node.js environment, meaning they won't be
exposed to the browser. In order to expose a variable to the browser
you have to prefix the variable with NEXT_PUBLIC_
:
所以改变
API_ENDPOINT = "http://localhost:4200/api/"
到
NEXT_PUBLIC_API_ENDPOINT = "http://localhost:4200/api/"
和
axios.post(`${process.env.API_ENDPOINT}/login`, data)
到
axios.post(`${process.env.NEXT_PUBLIC_API_ENDPOINT }/login`, data)
在我的应用程序中,我在 .env.local 文件中创建了一个环境变量,并通过 process.env.ENV_KEY 将其提取到组件中。但它没有返回实际值,而是 returns 未定义值。
.env.local
API_ENDPOINT = "http://localhost:4200/api/"
在组件中我得到的值是 process.env.API_ENDPOINT
但它 returns 是 undefined
App.js
function App(props) {
const loginUser = async event => {
event.preventDefault()
axios.post(`${process.env.API_ENDPOINT}/login`, data)
.then((response) => {
router.push('/')
})
}
}
我也尝试过配置到 env.js 文件中,但也没有任何效果。
exports.env = {
API_ENDPOINT: process.env.API_ENDPOINT
}
And into component have imported as
import {env} from './config.js'
function App(props) {
const loginUser = async event => {
event.preventDefault()
axios.post(`${env.API_ENDPOINT}/login`, data)
.then((response) => {
router.push('/')
})
}
}
此外,我还尝试创建一个构建,然后 运行 项目,然后还尝试创建 returns undefined
值。
我查看的参考资料
- Nextjs env variable is always undefined
- https://nextjs.org/docs/basic-features/environment-variables#loading-environment-variables
By default all environment variables loaded through .env.local are only available in the Node.js environment, meaning they won't be exposed to the browser. In order to expose a variable to the browser you have to prefix the variable with
NEXT_PUBLIC_
:
所以改变
API_ENDPOINT = "http://localhost:4200/api/"
到
NEXT_PUBLIC_API_ENDPOINT = "http://localhost:4200/api/"
和
axios.post(`${process.env.API_ENDPOINT}/login`, data)
到
axios.post(`${process.env.NEXT_PUBLIC_API_ENDPOINT }/login`, data)