【问题标题】:NextJS process.env. variables undefined on button click fetch dataNextJS process.env。按钮上未定义的变量单击获取数据
【发布时间】:2021-05-28 00:24:00
【问题描述】:

我遇到了 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: "" };
    });
};

【问题讨论】:

    标签: node.js reactjs environment-variables next.js nestjs


    【解决方案1】:

    根据docs,您可以使用NEXT_PUBLIC_ 前缀将Environment Variables 暴露给浏览器:

    env.local

    NEXT_PUBLIC_contentKey=somevalue
    

    用途:

    process.env.NEXT_PUBLIC_contentKey
    

    其他方法:

    next.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;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-23
      • 2021-07-02
      • 1970-01-01
      • 2021-08-15
      • 1970-01-01
      • 2019-02-03
      相关资源
      最近更新 更多