gpt4 book ai didi

node.js - NextJS process.env。按钮上 undefined variable 单击获取数据

转载 作者:行者123 更新时间:2023-12-04 01:06:11 37 4
gpt4 key购买 nike

我遇到了 ENV 变量的问题。
在第一个请求中:

export const getStaticProps = async () => {
const posts = await getPosts(1);
return { props: posts, revalidate: 5 };
};
一切顺利,它获取了所有数据,但是在单击按钮时,我想获取新数据,结果是 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)
正如您所看到的 env 变量导致 undefined ,我不知道为什么。
我如何获取数据:
  const fetchNewData =async (currentPage)=>{
console.log(currentPage);
const post = await getPosts(currentPage)
console.log(post);
}

我如何使用环境
export const CONTENTKEY=process.env.contentKey
export const BLOG_API = process.env.blogApiLink;
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: "" };
});
};

最佳答案

根据 docs您可以使用 NEXT_PUBLIC_暴露前缀 Environment Variables到浏览器:
环境.local

NEXT_PUBLIC_contentKey=somevalue
用:
process.env.NEXT_PUBLIC_contentKey
其他方法:
下一个.config.js
module.exports = {
publicRuntimeConfig: {
contentKey: process.env.contentKey,
blogApiLink: process.env.blogApiLink,
}
}
访问环境变量值:
import getConfig from "next/config";
const { publicRuntimeConfig } = getConfig();

export const CONTENTKEY= publicRuntimeConfig.contentKey
export const BLOG_API = publicRuntimeConfig.blogApiLink;

关于node.js - NextJS process.env。按钮上 undefined variable 单击获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66371967/

37 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com