简体   繁体   English

尚未设置Express.js httpOnly cookie

[英]Express.js httpOnly cookie not being set

I've set up an API with a create user and an auth route. 我已经使用创建用户和身份验证路由设置了API。 The auth route should set an httpOnly cookie containing a JWT, and should send JSON for the client to store in localhost. auth路由应设置一个包含JWT的httpOnly cookie,并应发送JSON供客户端存储在localhost中。

In the front-end I'm doing a simple fetch. 在前端,我正在做一个简单的提取。

The server responds 200 and with the JSON I expect, but somehow, the cookie doesn't get set. 服务器响应200并使用我期望的JSON,但不知何故,cookie未被设置。

However, in Postman, the cookie does indeed get set. 但是,在Postman中,cookie的确设置了。

Express server 快递服务器

const express = require('express')
const cors = require('cors')

// boilerplate stuff

app.use(express.json())
app.use(cors({ origin: 'http://localhost:3000', credentials: true }))

app.post('auth', (req, res) => {
  // fetch user from db, validation, bla bla bla

  const token = jwt.sign({ issuer: user.id }, keys.private, { algorithm: 'RS256' })

  res.cookie('token', token, { httpOnly: true })
  res.json(user)
})

Next.js front-end Next.js前端

const handleSubmit = async (e) => {
  e.preventDefault()
  try {
    const res = await fetch('http://localhost:5000/api/v1/auth', {
      method: 'post',
      mode: 'cors',
      credentials: 'include',
      headers: {
        'content-type': 'application/json',
        'accept': 'application/json',
      },
      body: JSON.stringify(formState),
    })
    const data = await res.json()
    console.log(data)
  } catch (err) {
    console.error(err)
    setError(err.message)
  }
}

'Twas resolved. '解决了。

I was looking in Session Storage as opposed to Cookies in my devtools. 我一直在寻找Session Storage,而不是在我的devtools中使用Cookies。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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