【问题标题】:How to add middleware to get serverSideProps in next js如何在下一个js中添加中间件来获取serverSideProps
【发布时间】:2021-02-12 23:22:46
【问题描述】:

我需要在这个函数上添加一些node js中间件

export async function getServerSideProps(ctx) {

  console.log('coo',cookieParser(ctx.req.headers.cookie));
  console.log('headers', ctx.req.headers.cookie);
 const res = await fetch('http://localhost:1337/publics')
 const data = await res.json()
 const theData = data[ctx.query.id - 1]

 return {
    props: {data: theData}, 
  }
}

我需要使用cookie解析器中间件,这里有没有添加中间件,如果没有,我如何从cookie中获取信息

【问题讨论】:

  • 默认情况下,您已经可以访问getServerSideProps 中的req.cookies

标签: node.js reactjs next.js


【解决方案1】:

您可以使用nookies,例如:

import nookies from 'nookies'

export default function Me() {
  return <div>My profile</div>
}

export async function getServerSideProps(ctx) {
  // Parse
  const cookies = nookies.get(ctx)

  // Set
  nookies.set(ctx, 'fromGetInitialProps', 'value', {
    maxAge: 30 * 24 * 60 * 60,
    path: '/',
  })

  // Destroy
  // nookies.destroy(ctx, 'cookieName')

  return { cookies }
}

【讨论】:

    猜你喜欢
    • 2022-12-25
    • 2022-01-02
    • 1970-01-01
    • 2023-01-19
    • 2020-07-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-28
    相关资源
    最近更新 更多