[英]How to use cookie inside `getServerSideProps` method in Next.js?
I have to send current language on endpoint.我必须在端点上发送当前语言。 But getting language from Cookie returns undefined inside
getServerSideProps
.但是从 Cookie 获取语言在
getServerSideProps
中返回 undefined 。
export async function getServerSideProps(context) {
const lang = await Cookie.get('next-i18next')
const res = await fetch(`endpoint/${lang}`)
const data = await res.json()
return {
props: { data },
}
}
export default Index;
What is the proper way to get cookie inside getServerSideProps
?在
getServerSideProps
中获取 cookie 的正确方法是什么?
You can get the cookies from the req.headers
inside getServerSideProps
:您可以从
getServerSideProps
的req.headers
获取 cookie:
export async function getServerSideProps(context) {
const cookies = context.req.headers.cookie;
return {
props: {},
};
}
You could then use the cookies npm package to parse them:然后你可以使用cookies npm 包来解析它们:
import * as cookie from 'cookie'
export async function getServerSideProps(context) {
const parsedCookies = cookie.parse(context.req.headers.cookie);
return { props: {} }
}
You can use parseCookies
function with cookie package您可以将
parseCookies
函数与cookie包一起使用
import cookie from "cookie"
function parseCookies(req){
return cookie.parse(req ? req.headers.cookie || "" : document.cookie);
}
And then get access like that.然后像这样获得访问权限。
export async function getServerSideProps({ req} ) {
const cookies = parseCookies(req);
// And then get element from cookie by name
return {
props: {
jwt: cookies.jwt,
}
}
}
how are you doing?你好吗? you can use Something like this:
你可以使用这样的东西:
export async function getServerSideProps(context) {
console.log(context.req.cookies)
}
so easy and so beautifuly!如此简单,如此美丽!
To avoid having to parse the cookies string from context.req.headers.cookie
, Next.js also provides the cookies as an object which can be accessed with context.req.cookies
.为了避免从
context.req.headers.cookie
解析 cookie 字符串,Next.js 还提供了 cookie 作为可以通过context.req.cookies
访问的对象。
export async function getServerSideProps(context) {
const lang = context.req.cookies['next-i18next']
// ...
}
If you are using Axios this is very simple如果您使用的是 Axios 这很简单
getServerSideProps
method.getServerSideProps
方法中起作用。 You can't get access to the cookie by using withCredentials because this is on the server.const { token } = context.req.cookies;
const response = await axios.get('/staff/single', {
headers: { Cookie: `token=${token};` },
});
const response = await axios.get('/staff/single', {
headers: { withCredentials: true },
});
We can get the cookies from the req.headers inside getServerSideProps without npm我们可以从没有npm的 getServerSideProps 中的 req.headers 中获取cookies
export async function getServerSideProps(ctx) {
const data = ctx.req?.cookies['CookiesName'];
OR
const data_1 = ctx.req?.cookies?.CookiesName;
console.log(data, data_1)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.