Node.js 如何在 post 请求(登录)后发送 HttpOnly cookie?

Node.js how do you send a HttpOnly cookie after a post request (login)?

Goal/Problem

我想知道如何在 post(login) 请求后发送 HttpOnly cookie。我想我知道如何创建一个。问题是我无法在我的 post(login) 路线中创建一个。

我试过的

我尝试在 post 上创建一个 HttpOnly cookie,但失败了。然后我意识到执行 get 路由会创建我的 HttpOnly cookie。我也尝试对我的 get 路线执行 next() 但我无法让它工作。我还尝试将 post(login) 更改为 get,但我 运行 遇到了我在 req.body 上传递的数据是“未定义”的问题。

Cookie 路由(使用“cookie”和“express”包)

  router.get('/setcookie', (req, res)=>{ 
    res.setHeader('Set-Cookie', cookie.serialize('name', "secretcookie", {
      httpOnly: true,
      maxAge: 60 * 60 * 24 * 7
    }));
    next();
  }); 

登录路径

router.post("/login", (req, res, next) => {
    var username = req.body.username;
    var password = req.body.password;

    var sql = "SELECT * FROM user_tables where user_tables.Name = '" + username + "' AND user_tables.Password='" + password + "'";
    connectsql.query(sql, function (err, rows, fields) {
            if (rows.length === 1) {
                console.log(sql);
                console.log(rows[0].ID);
                const token = jwt.sign({P_id: rows[0].ID, P_username: username}, process.env.TOKEN_SECRET, {expiresIn: "2m"});
            } 
            else {
                console.log(sql);
                console.log("authentication failed"); //send  response of 401 for auth failed
            }
        })
})

非常感谢您的帮助!如果有更好的方法,请告诉我。

您的 login 路由中的处理程序未返回任何内容。您必须使用 res object 中的 cookie 设置 header 并调用 res.end()next()。 假设你正在使用 express 它应该是这样的。

const express = require('express')
const cookie = require('cookie')

const app = express()

app.get('/', (req, res, next) => {
  return res.send(`<form method="POST" action="/login"><button type=submit>LOGIN!!</button></form>`)
})

app.post('/login', (req, res, next) => {
  res.setHeader('Set-Cookie', cookie.serialize('foo', 'bar', { httpOnly: true }))
  return res.send(`<body><h1>SUCCESS!!</h1></body>`);
})

app.listen(8000, () => console.log('listening'))