简体   繁体   English

如何在 Next.js 的 getServerSideProps 方法中使用 cookie?

[英]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 :您可以从getServerSidePropsreq.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 这很简单

  • This will work inside getServerSideProps method.这将在getServerSideProps方法中起作用。 You can't get access to the cookie by using withCredentials because this is on the server.您无法使用 withCredentials 访问 cookie,因为它位于服务器上。
const { token } = context.req.cookies;
  const response = await axios.get('/staff/single', {
    headers: { Cookie: `token=${token};` },
  });
  • or try (This will work on the client)或尝试(这将在客户端工作)
  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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM