我可以更改特定文件中的变量并在 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路径访问测试:)
您可以查看以下文件。
如果你能告诉我我实施的闭包是否有任何问题,或者是否还有其他任何可以实现我的目标的东西,那将是非常有帮助的。
下面是代码。
import axios from "axios";
const backendFetcherCloser = (cookies?: string) => {
const fetcher = axios.create({
baseURL: process.env.NEXT_PUBLIC_BACKEND_API_URL,
withCredentials: true,
headers: {
Cookie: cookies,
},
});
return {
setCookie: (_cookie: string) => (cookies = _cookie),
getCookie: () => cookies,
instance: () => fetcher,
};
};
const backendFetcher = backendFetcherCloser();
export default backendFetcher;
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).*)",
],
};
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() })
}