【问题标题】:HttpOnly cookie not being sent to apiHttpOnly cookie 未发送到 api
【发布时间】:2021-08-05 15:53:12
【问题描述】:

我正在使用 next.js 和strapi。 我正在尝试在我的下一个 js 前端和我的 Strapi 应用程序之间设置一个 httpOnly cookie。

cookie 由后端接收,但是当我尝试向后端发出请求时 - cookie 不存在。但是,当我使用邮递员时,cookie 集是存在的。

Strapi 应用:

  const t = await ctx.cookies.get('mytest') // prints undefined with next js but works with postman
  console.log(t);
  ctx.cookies.set('mytest', '123', {
    httpOnly: true,
    maxAge: 1000 * 60 * 60 * 24 * 365,
    secure: false,
  })

next.js 前端:

export default function Home(props: any) {

  async function onClick() {
    const options = {
      method: 'GET',
      'Access-Control-Allow-Credentials': true,
      withCredenitals: true
    }
    const test = await fetch('http://localhost:1337/endpoint', options as any)
    const res = await test.json()

  }

  return (
    <div>

      <div onClick={onClick}>
        Make a fetch to the api
      </div>
    </div>
  )
}

我尝试过的事情:

  1. 设置允许使用 cors 的特定域
  2. 将 api 调用移至 getServerSideProps 函数
  3. 从 next.js api 路由进行 api 调用
  4. 我尝试从普通的 html 文件发出请求,但它仍然无法正常工作,所以我现在假设这不是下一个 js 问题,因为无论如何它都是客户端。继承人的 HTML 代码不起作用 - 我得到了 cors 错误,然后当我没有时 - 我仍然没有得到 cookie 显示
    const options = {
      method: 'get',
      mode: 'cors', // no-cors, *cors, same-origin
      cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
      credentials: 'include', // include, *same-origin, omit
      withCredentials: true,
      headers: {
        'Content-Type': 'application/json',
        'Access-Control-Allow-Credentials': true,
        "Access-Control-Allow-Origin": "http://127.0.0.1:1337/myapi"
      },
    }

    const req = await fetch('http://127.0.0.1:1337/myapi', options)
    const res = await req.json()
  1. 更改了标头在后端发回的方式
  console.log(t);
  ctx.cookies.set('mytest', '123', {
    httpOnly: true,
    maxAge: 1000 * 60 * 60 * 24 * 365,
    secure: false,
  })
  ctx.response.header = {
    ...ctx.response.header,
    'Access-Control-Allow-Credentials': true,
    'Access-Control-Allow-Origin': ctx.request.headers.origin,
    'Access-Control-Allow-Methods': 'GET,PUT,POST,DELETE,UPDATE,OPTIONS',
    'Access-Control-Allow-Headers': 'X-Requested-With, X-HTTP-Method-Override, Content-Type, Accept'
  }

运气不好。

谁能告诉我发生了什么?我一直在寻找几个小时,但似乎没有任何工作

【问题讨论】:

    标签: reactjs cookies next.js strapi httponly


    【解决方案1】:

    我最终解决了这个问题 - 实际上是因为 cookie 没有保存到我的浏览器中。

    有两个问题:

    1. 需要凭据,因为这是一个跨源请求,并且要发送 cookie 我必须明确说明
    credentials: 'include',
    
    1. 在服务器上,我必须说明来源来自哪里
    ctx.set('Access-Control-Allow-Origin', ctx.request.headers.origin)
    

    希望这会有所帮助,并且您不要花费 8 个小时来随机记录控制台内容

    【讨论】:

      猜你喜欢
      • 2020-11-19
      • 2021-08-26
      • 2011-07-22
      • 2022-01-03
      • 2018-03-18
      • 2019-01-27
      • 1970-01-01
      • 2020-03-12
      • 1970-01-01
      相关资源
      最近更新 更多