表单应用程序中缺少环境变量

问题描述 投票:0回答:1

我正在制作 Next.js 应用程序并尝试制作 CRUD 功能。

当我创建如下代码的“创建”页面时,出现错误。 看起来像是 env 检测问题。

顺便说一句,我正在使用 microCMS 作为 API。

我不知道如何解决它。请告诉我怎么做。 预先感谢。

Can't detect env variable

.env.development.local

MICROCMS_SERVICE_DOMAIN=(some domain)
MICROCMS_API_KEY=(some key)

libs/client.js

import { createClient } from 'microcms-js-sdk';

export const client = createClient({
  serviceDomain: process.env.MICROCMS_SERVICE_DOMAIN, 
  apiKey: process.env.MICROCMS_API_KEY,
  retry: true 
});

我的表单代码是这样的。 页面/博客/create.js

import Link from "next/link";
import { client } from "../../libs/client";
import { useRouter } from "next/router";

export default function Create () {
    const router = useRouter()
    const create = async (e) => {
  
      const title = "aaaa";
      const content = "bbbb";

      client.create({
        endpoint: "blogs",
        content: {
          title: title,
          content: content,
        }
      }).then((res) => {
        if (res.status === 401) {
          alert("登録ができませんでした。")
        } else {
          alert("登録されました。")
          router.push(`/`)
        }
      })
    }

  return (
    <>
      <div className='main'>
        <h1 className=''>投稿ページ</h1>

        {/* TOPに戻るボタン */}
        <div className="top">
          <Link href="/" className="">
            <button className="">Topに戻る</button>
          </Link>
        </div>

        <div className="contents">
            <div>
                <h2>タイトル</h2>
                <input name="title" type="text" />
                
            </div>
            <div>
            <h2>コンテンツ</h2>
                <textarea name="content" ></textarea>
            </div>

            <div>
                <form onSubmit={ create }>
                <button type="submit">
                    <p>登録する</p>
                </button>
                </form>
            </div>
        </div>
      </div>
    </>
  );
}
javascript reactjs next.js
1个回答
0
投票

您必须将

NEXT_PUBLIC_
添加到要在客户端中访问的环境变量。

NEXT_PUBLIC_MICROCMS_SERVICE_DOMAIN=(some domain)
NEXT_PUBLIC_MICROCMS_API_KEY=(some key)

非 NEXT_PUBLIC_ 环境变量仅在 Node.js 环境中可用,这意味着浏览器无法访问它们(客户端在不同的环境中运行)。

来源:https://nextjs.org/docs/pages/building-your-application/configuring/environment-variables#bundling-environment-variables-for-the-browser

© www.soinside.com 2019 - 2024. All rights reserved.