使用cookie-parser时无法存储cookie客户端

时间:2018-02-09 22:19:31

标签: javascript reactjs cookie-session

我很难让我的反应应用程序使用cookie会话。 当我查看我的网络和注册时,我发送了一个Set-Cookie。这些是我的回复标题:

 Connection:keep-alive
Content-Type:application/json
Date:Fri, 09 Feb 2018 22:32:02 GMT
Set-Cookie:session=eyJ1c2VySWQiOjEwOX0=; path=/; expires=Mon, 19 Feb 2018 22:32:02 GMT; httponly
Set-Cookie:session.sig=o975QwcyzldDFzSPzbp2S4Qe_M4; path=/; expires=Mon, 19 Feb 2018 22:32:02 GMT; httponly
Transfer-Encoding:chunked
X-Powered-By:Express

请求标题:

Accept:application/json
Accept-Encoding:gzip, deflate, br
Accept-Language:en-US,en;q=0.9
Connection:keep-alive
Content-Length:59
Content-Type:application/json
Host:localhost:5000
Origin:http://localhost:5000
Referer:http://localhost:5000/signup
User-Agent:Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.140 Safari/537.36

但是,我注意到我的cookie没有存储在浏览器中。我相信cookie应该由浏览器自动存储?继承我的代码:

const express = require('express')
const bodyParser = require('body-parser')
const cookieParser = require('cookie-parser')
const cookieSession = require('cookie-session')
const bcrypt = require('bcrypt')
const port = process.env.PORT || 5000
const app = express()
const pg = require('pg')
const conString = "postgres://postgres:postgres@localhost:5432/test"
const db = new pg.Client(conString)
let User


app.use(bodyParser.urlencoded({ extended: true }))
app.use(cookieParser())
app.use(cookieSession({
    name: 'session',
    secret: "booboo",
    httpOnly: true,
    // Cookie Options
    maxAge: 24 * 60 * 60 * 1000 * 10 // 24 hours * 10 days
  }))

app.use(express.json())
app.use(express.static(__dirname + '/client/build'))

app.use(function(req,res ,next){
console.log(req.session)
if(req.method !== 'POST')
    res.sendFile(__dirname + '/client/build/index.html')

if(req.headers.accept === 'application/json')
    next() 
})


app.route('/signup')
    .post((req, res) => {
        const sendError = (msg) => {
            res.status(400).send({error: msg})
        }

        if(!User.validateBeforeCreate({email: req.body.user.email, password: req.body.user.password}, sendError))
            return

        const salt = bcrypt.genSaltSync();
        const password = bcrypt.hashSync(req.body.user.password, salt);
        User.create({email: req.body.user.email, password: password}, (err, user) => {
            if(err !== null){
                if(err.code === '23505')
                    sendError('Account with that email already exists.')
            }
            else{
                req.session.userId = user.user_id
                res.writeHead(201, {"Content-Type": "application/json"})
                res.end()
                console.log(req.session)
                console.log(req.session.userId)
            }
        })
    })

注册中的我的console.log打印出来: 会话{userId:103} 103

同时我的console.log在我注册并访问一个页面以接收我的反应应用程序之后我打印出来(可能是因为浏览器没有cookie): Session {},我试过将httpOnly设置为true和false。相同的结果。

我做错了什么?

2 个答案:

答案 0 :(得分:0)

您似乎没有在Cookie对象中设置域名,因此浏览器会丢弃Cookie。我还建议您在浏览器中打开开发人员工具,并检查服务器发送的标头,以查看传输的cookie的样子。

尝试:

scanf

答案 1 :(得分:0)

我把头撞到键盘上几个小时后才发现它。出于某种原因,它不会设置cookie。得到了工作,但我花了一段时间才到达那里。我花了一段时间搞清楚它是否有反应。但不,如果我把它设置在get动作上它会起作用。所以我认为这是一个安全问题。我发现我需要在客户端的fetch上添加一个带有'same-origin'的凭证属性。我把下一个()放在错误的位置。现在一切正常。所以我所做的所有改变都是4行。感谢Taylor Swanson和这篇文章: Why is the browser not setting cookies after an AJAX request returns?

name: 'session',
secret: "booboo",
httpOnly: true,
path: "/",
domain: "localhost"

句柄提交是客户端回调:

handleSubmit = (event) => {
        event.preventDefault()
        fetch('/signup',{
            headers:{
              'Accept': 'application/json',
              'Content-Type': 'application/json'
            },
            credentials: 'same-origin',
            method: 'post',
            body: JSON.stringify({user: {...this.state}})
          })
    }

我的新服务器代码如下所示:

app.use(bodyParser.urlencoded({ extended: true }))
app.use(cookieParser())
app.use(cookieSession({
    name: 'session',
    secret: "booboo",
    httpOnly: true,
    path: "/",
    domain: "localhost"
    // Cookie Options
  }))

app.use(express.json())
app.use(function(req, res, next){
    if(req.method === 'GET' && req.cookies.session === undefined)
        req.session.userId = null
    else
        console.log(req.session.userId)

    next()
})
app.use(express.static(__dirname + '/client/build/'))
app.use(function(req,res ,next){
    if(req.method === 'GET')
        res.sendFile(__dirname + '/client/build/index.html')

    if(req.headers.accept === 'application/json')
        next()
})

app.route('/signup')
    .post((req, res, next) => {
        const sendError = (msg) => {
            res.status(400).send({error: msg})
        }

        if(!User.validateBeforeCreate({email: req.body.user.email, password: req.body.user.password}, sendError))
            return

        const salt = bcrypt.genSaltSync();
        const password = bcrypt.hashSync(req.body.user.password, salt);
        User.create({email: req.body.user.email, password: password}, (err, user) => {
            if(err !== null){
                if(err.code === '23505')
                    sendError('Account with that email already exists.')
            }
            else{
                req.session.userId = user.user_id
                res.writeHead(201, {"Content-Type": "application/json"})
                res.end()
                console.log(req.session)
                console.log(req.session.userId)
            }
            next()
        })
    })