标头中的令牌不起作用,即使令牌存储在 cookie 中也是如此

问题描述 投票:0回答:0

有谁知道如何将保存在cookies中的token设置到请求头中吗?当我登录该网站时,我可以从应用程序部分和 Cookies 访问令牌。但是我不能为其他请求设置它并得到“SyntaxError: Unexpected token < in JSON at position 0". Also consider that I am using fetch and Nextjs. This is my homepage:

export const getServerSideProps = async context => {
  const cookies = cookie.parse(context.req.headers.cookie || '')
  const token = cookies.access_token || TOKEN

  const productsSells = await fetch(`${server}/sellproducts`, {
    headers: {
      'Content-Type': 'application/json',
      Authorization: `Bearer ${token}`
    }
  })
  const sellsData = await productsSells.json()

  const personDetail = await fetch(`${server}/person`, {
    headers: {
      'Content-Type': 'application/json',
      Authorization: `Bearer ${token}`
    }
  })
  const personData = await personDetail.json()

  return {
    props: {
      sells: sellsData,
      person: personData
    }
  }
}

这是我的登录处理程序:

import cookie from 'cookie'

export default async function handler(req, res) {
  if (req.method === 'POST') {
    try {
      const resApi = await fetch('http://192.168.100.166:9000/api/login', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          Accept: 'application/json'
        },
        body: JSON.stringify({
          email: req.body.email,
          password: req.body.password
        })
      })

      const data = await resApi.json()

      console.log(data.access_token)

      if (resApi.ok) {

        res.setHeader(
          'Set-Cookie',
          cookie.serialize('access_token', data.access_token, {
            // httpOnly: true,

            secure: process.env.NODE_ENV !== 'development',
            path: '/home'
          })
        )

        res.status(200).json({ user: data.user })
      } else {
        res.status(resApi.status).json({ message: data })
      }
    } catch (e) {
      res.status(500).json({ message: { err: ['Server Error'] } })
    }
  } else {
    res.setHeader('Allow', ['POST'])
    res.status(405).json({ message: `Method ${req.method} not allowed` })
  }
}
authentication cookies next.js token bearer-token
© www.soinside.com 2019 - 2024. All rights reserved.