gpt4 book ai didi

javascript - Next.js getInitialProps cookies

转载 作者:行者123 更新时间:2023-12-03 22:46:50 24 4
gpt4 key购买 nike

我遇到了有关从 Next.js 中的 getInitialProps 函数获取数据的问题

场景是这样的:当用户第一次访问页面时,我向远程 API 发出 HTTP 请求,该 API 返回应用程序所需的数据。我在 getInitialProps 方法中发出请求,因为我希望在将内容发送给用户时完全呈现内容。

问题是,当我发出这个请求时,API 返回一个 session cookie,我需要将其存储在浏览器中,而不是呈现内容的服务器中。此 cookie 必须出现在未来客户端对 API 的请求中。否则,API 返回 403。

我的问题是:如果我从服务器执行这个请求,并且因此响应也返回到服务器,我如何为浏览器设置 cookie 以便我可以向客户端发出请求API?

我尝试操纵 cookie 的 domain 选项,但我无法设置另一个域。浏览器会忽略它。

这是我的 getInitialProps 的样子:

static async getInitialProps(appContext) {
const { Component, ctx, router } = appContext;
const { store } = ctx;
let pageProps = {};

if (Component.getInitialProps) {
pageProps = await Component.getInitialProps(appContext);
}

const { hotelId, reservationId } = router.query;

if (!hotelId || !reservationId) return { pageProps };

// Fetching reservation and deal data
try {
const { data, errors, session } = await fetchData(hotelId, reservationId);

if (data) {
store.dispatch(storeData(data));
}

// This works, but the domain will be the frontend server, not the API that I connecting to the fetch the data
if (session) {
ctx.res.setHeader('Set-Cookie', session);
}

// This doesn't work
if (session) {
const manipulatedCookie = session + '; Domain: http://exampe-api.io'
ctx.res.setHeader('Set-Cookie', manipulatedCookie);
}

if (errors && errors.length) {
store.dispatch(fetchError(errors));
return { errors };
} else {
store.dispatch(clearErrors());
return {
...pageProps,
...data
};
}
} catch (err) {
store.dispatch(fetchError(err));

return { errors: [err] };
}

return { pageProps };
}

fetchData 函数只是一个向 API 发送请求的函数。我从响应对象中提取 cookie,然后将其分配给 session 变量。

最佳答案

getInitialProps 在客户端和服务器上执行。所以当你写你的抓取函数时,你有条件地抓取。因为如果您在服务器端发出请求,则必须输入绝对 url,但如果您在浏览器上,则使用相对路径。您必须注意的另一件事是,当您发出请求时,您必须自动附加 cookie。

在您的示例中,您正尝试从 _app.js 发出请求。 Next.js 使用 App 组件来初始化页面。因此,如果您想在页面上显示一些 secret 数据,请在该页面上进行。 _app.js 是所有其他组件的包装器,您从 _app.js 的 getInitialProps 函数返回的任何内容都将可用于应用程序中的所有其他组件。但是如果你想在授权时在组件上显示一些 secret 数据,我认为最好让那个组件来获取数据。想象一个用户登录他的帐户,您必须仅在用户登录时获取数据,因此其他不需要身份验证的端点将无法访问该 secret 数据。

假设一个用户登录了,你想获取他的 secret 数据。假设你有 page/secret 所以在那个组件里面我可以这样写:

Secret.getInitialProps = async (ctx) => {
const another = await getSecretData(ctx.req);

return { superValue: another };
};

getSecretData() 是我们应该获取 secret 数据的地方。抓取操作通常存储在/actions/index.js 目录中。现在我们到这里来编写我们的获取函数:

 // Since you did not mention which libraries you used, i use `axios` and `js-cookie`. they both are very popular and have easy api.
import axios from "axios";
import Cookies from "js-cookie";


//this function is usually stored in /helpers/utils.js
// cookies are attached to req.header.cookie
// you can console.log(req.header.cookie) to see the cookies
// cookieKey is a param, we pass jwt when we execute this function
const getCookieFromReq = (req, cookieKey) => {
const cookie = req.headers.cookie
.split(";")
.find((c) => c.trim().startsWith(`${cookieKey}=`));

if (!cookie) return undefined;
return cookie.split("=")[1];
};

//anytime we make request we have to attach our jwt
//if we are on the server, that means we get a **req** object and we execute above function.
// if we do not have req, that means we are on browser, and we retrieve the cookies from browser by the help of our 'js-cookie' library.
const setAuthHeader = (req) => {
const token = req ? getCookieFromReq(req, "jwt") : Cookies.getJSON("jwt");

if (token) {
return {
headers: { authorization: `Bearer ${token}` },
};
}
return undefined;
};

//this is where we fetch our data.
//if we are on server we use absolute path and if not we use relative
export const getSecretData = async (req) => {
const url = req ? "http://localhost:3000/api/v1/secret" : "/api/v1/secret";
return await axios.get(url, setAuthHeader(req)).then((res) => res.data);
};

这就是你应该如何在 next.js 中实现获取数据

关于javascript - Next.js getInitialProps cookies,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56315965/

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