Sin*_*ngh 5 environment-variables node.js reactjs next.js nestjs
我遇到 ENV 变量问题。在第一次请求时:
export const getStaticProps = async () => {
const posts = await getPosts(1);
return { props: posts, revalidate: 5 };
};
Run Code Online (Sandbox Code Playgroud)
一切都很顺利,它获取了所有数据,但是单击按钮时我想获取新数据,但得到了 404 :
xhr.js:177 GET http://localhost:3000/fr/undefined/ghost/api/v3/content/posts?key=undefined&fields=id%2Ctitle%2Cfeature_image%2Cslug%2Cexcerpt%2Ccustom_excerpt%2Creading_time%2Ccreated_at&include=authors%2Ctags&page=2 404 (Not Found)
Run Code Online (Sandbox Code Playgroud)
正如您所看到的 env 变量结果为 undefined ,我不知道为什么。我如何获取数据:
const fetchNewData =async (currentPage)=>{
console.log(currentPage);
const post = await getPosts(currentPage)
console.log(post);
}
Run Code Online (Sandbox Code Playgroud)
我如何使用环境
export const CONTENTKEY=process.env.contentKey
export const BLOG_API = process.env.blogApiLink;
Run Code Online (Sandbox Code Playgroud)
import axios from "axios";
import {BLOG_API,CONTENTKEY} from "../segret_keys"
export const getPosts = async (page) => {
const pageUrl =
BLOG_API +
"/ghost/api/v3/content/posts/?key=" +
CONTENTKEY +
"&fields=id,title,feature_image,slug,excerpt,custom_excerpt,reading_time,created_at&include=authors,tags&page=" +
page;
console.log(pageUrl);
return axios({
method: "get",
url: pageUrl,
}) //&filter=tag:blog,tag:Blog
.then((res) => {
return { status: res.status, data: res.data };
})
.catch((err) => {
console.log(err.response.status, err.response.data);
return { status: err.response.status, data: "" };
});
};
Run Code Online (Sandbox Code Playgroud)
根据文档,您可以使用前缀向浏览器NEXT_PUBLIC_
公开:Environment Variables
本地环境
NEXT_PUBLIC_contentKey=somevalue
Run Code Online (Sandbox Code Playgroud)
使用:
process.env.NEXT_PUBLIC_contentKey
Run Code Online (Sandbox Code Playgroud)
其他方法:
next.config.js
module.exports = {
publicRuntimeConfig: {
contentKey: process.env.contentKey,
blogApiLink: process.env.blogApiLink,
}
}
Run Code Online (Sandbox Code Playgroud)
访问环境变量值:
import getConfig from "next/config";
const { publicRuntimeConfig } = getConfig();
export const CONTENTKEY= publicRuntimeConfig.contentKey
export const BLOG_API = publicRuntimeConfig.blogApiLink;
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
2187 次 |
最近记录: |