我可以在 JavaScript 中更改特定文件中的变量并在另一个文件中读取它吗?

Can I change the variable in a specific file and read it in another file in JavaScript?

提问人:Jay-flow 提问时间:3/17/2023 最后编辑:Jay-flow 更新时间:3/17/2023 访问量:55

问:

我可以在 JavaScript 中更改特定文件中的变量并在另一个文件中读取它吗?

使用 Next.js 时,我必须在从后端发送请求时在 axios 中设置 cookie 值,但我不想每次都把 cookie 值作为一个因素,所以设置好后,我将只通过调用函数来发送请求。

所以我通过闭包实现了它,但是在同一文件中输出 cookie 值没有任何问题,但从另一个文件导入时设置的 cookie 值不会输出。

我把代码放在 Codesandbox 中,所以请检查一下。https://codesandbox.io/p/sandbox/amazing-field-4hos49?file=%2Fpages%2Fapi%2Ftest.ts&selection=%5B%7B%22endColumn%22%3A23%2C%22endLineNumber%22%3A10%2C%22startColumn%22%3A23%2C%22startLineNumber%22%3A10%7D%5D

您可以通过 https://4hos49-3000.csb.app/api/test 路径:)访问测试

您可以查看下面的文件。

  • API/index.ts
  • 页面/API/test.ts
  • middleware.ts

如果您能告诉我我实施的闭包是否有任何问题,或者是否有任何其他可以实现我的目标,那将是非常有帮助的。

下面是代码。

  • API/index.ts
import axios from "axios";

const backendFetcherCloser = (cookies?: string) => {
  return {
    setCookie: (_cookie: string) => (cookies = _cookie),
    getCookie: () => cookies,
    instance: () => axios.create({
      baseURL: process.env.NEXT_PUBLIC_BACKEND_API_URL,
      withCredentials: true,
      headers: {
        Cookie: cookies,
      },
    }),
  };
};

const backendFetcher = backendFetcherCloser();

export default backendFetcher;
  • middleware.ts
import { NextRequest } from "next/server";
import backendFetcher from "./apis";

const middlewareAPI = async (req: NextRequest) => {
  backendFetcher.setCookie("test");
  console.log(backendFetcher.getCookie()); // The 'test' is output.
};

export const middleware = async (req: NextRequest) => {
  if (req.nextUrl.pathname.startsWith("/api")) {
    return await middlewareAPI(req);
  }
};

export const config = {
  matcher: [
    "/((?!_next|kakao|robots.txt|favicon.ico|apple-touch-icon.png|apple-touch-icon-precomposed.png).*)",
  ],
};
  • 页面/API/test.ts
import type { NextApiRequest, NextApiResponse } from "next";
import backendFetcher from "../../apis";

type Data = {
  cookie: string | undefined;
};

export default function handler(
  req: NextApiRequest,
  res: NextApiResponse<Data>
) {
  // I expect the test to be printed out, but it does not.
  res.status(200).json({ cookie: backendFetcher.getCookie() })
}
JavaScript 节点:.js 下一个 .js 闭包

评论


答: 暂无答案