【问题标题】:Cannot read cookie from express无法从 express 中读取 cookie
【发布时间】:2020-11-25 01:47:01
【问题描述】:

我正在构建一个身份验证微服务;客户端在codesandbox上,服务器端在repl上

我正在尝试将访问令牌存储在服务器端(仅限 http)

我已经设置了 cookie 解析器

//COOKIE
const cookieParser = require('cookie-parser');
app.use(cookieParser());

我这样发送cookie

res.cookie("access_token", access_token,cookieOptions)
.status(200)
.send({success: true,token_type:"bearer",
expires_in: new Date(Date.now() + 60 * 1000 ),
refresh_token: refresh_token})

这是客户端

function fetch_profile_accountInfo(username, password) {
      let url = "https://repl.co/api/auth/localLogin";
      return axios
      .post(url, {
           username: username.toLowerCase(),
           password: password
      })
      .then((res) => res.data);
      }
} 

function getCookie(cname) { 
     var name = cname + "="; var decodedCookie = decodeURIComponent(document.cookie); 
     var ca = decodedCookie.split(";"); 
     for (var i = 0; i < ca.length; i++) { 
           var c = ca[i]; 
           while (c.charAt(0) === " ") { 
                c = c.substring(1); 
           } 
           if (c.indexOf(name) === 0) { 
                return c.substring(name.length, c.length); 
           } 
     } 
     return ""; 
}

let { refresh_token, expires_in } = await fetch_profile_accountInfo(
 username,
 password
}

const access_token = getCookie("access_token"); 
console.log("document: " + document.cookie); 
console.log("access_token: " + access_token);

当我调用 document.cookie 时,我得到 null 或 undefined

我也试过设置 axios 使用 withCredentials: true

function fetch_profile_accountInfo(username, password) {
 let url = "https://repl.co/api/auth/localLogin";
 return axios
 .post(url, {
      username: username.toLowerCase(),
      password: password
 }, {withCredentials: true} )
 .then((res) => res.data);
}

但我遇到网络错误

有谁知道如何解决这个问题以从 express 获取 cookie?

另外我也想问一下,把access token存放在server cookie上,refresh token存放在client端localstorage上好不好?

谢谢

【问题讨论】:

    标签: node.js express cookies


    【解决方案1】:

    如果 cookie 是 httpOnly,它不能在客户端使用,只能在服务器端使用,因此请确保在 cookieOptions 变量中设置 httpOnly:false

    【讨论】:

    • 谢谢回复。我只是设置为 false,但仍然无法读取 cookie。而且从我看的教程来看,设置httpOnly为true可以防止通过JS访问,使其免疫XSS攻击。
    • @chikarau 您是否在 chrome 开发工具中检查了控制台?它可能会告诉你出了什么问题。
    • 在开发工具的应用程序选项卡中设置 cookie。然后在控制台选项卡中检查您的 fetch_profile 函数是否获取 cookie。
    • 如果我添加了“withCredentials: true”,它会给我一个错误说“已被 CORS 策略阻止”,但我已经导入了 cors()
    猜你喜欢
    • 1970-01-01
    • 2016-05-29
    • 2022-01-12
    • 1970-01-01
    • 2020-04-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多