【发布时间】:2019-10-12 10:23:49
【问题描述】:
我遇到了关于从 Next.js 中的 getInitialProps 函数获取数据的问题
场景是这样的:当用户第一次访问页面时,我向远程 API 发出 HTTP 请求,该 API 返回应用程序所需的数据。我在 getInitialProps 方法中发出请求,因为我希望在将内容发送给用户时完全呈现内容。
问题是,当我发出这个请求时,API 会返回一个会话 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 变量。
【问题讨论】:
-
如果您的 API 在不同的域上,在其他域上设置 cookie 是有问题的,请考虑安全性,如果允许,您可以在 facebook.com 的行为上设置 cookie :]
标签: javascript authentication cookies next.js server-side-rendering