【问题标题】:How do I fetch cookie data with React?如何使用 React 获取 cookie 数据?
【发布时间】:2019-01-01 12:04:54
【问题描述】:

我有一个 MERN + Passport.js 应用程序,它使用 fetch 调用我的 express API 以检索存储在 cookie 中的数据。我的 React 前端路由到 localhost:3000,我的后端路由到 localhost:3001。我的 cookie 没有被保存,因此我的会话没有在我的浏览器中持续存在。这不是 express-sessions 或护照中间件的问题,因为当我使用 POSTMAN 执行对我的 API 的必要调用时,cookie 被存储并且会话持续存在。 只有当我尝试将这些信息通过/传递到我的前端时才会出现问题。我被难住了一段时间,似乎无法在任何地方找到答案。

这是我用来保存 cookie 的行:

handleLogin(event) {
        event.preventDefault();
        fetch("http://localhost:3001/users/login", {
            // credentials: 'include',
            credentials: 'same-origin',
            method: "post",
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json'
            },   
        body: JSON.stringify({
            username: this.state.username,
            password: this.state.password
            })
        })
        // .then( (response) => response.json())
        .then( (response )=> {
            if(response.message){
                alert(response.message);
            }
        })

正确调用我的 API,记录当前会话、用户数据和 cookie。

刷新并发出另一个请求后,我丢失了 cookie(我认为它从一开始就没有正确存储)和所有会话数据。

这是我在导航到新页面时发出的获取请求:

componentDidMount(){
        var current_user = "";
        fetch("http://localhost:3001/users/", {
            // credentials: 'include',
            credentials: 'same-origin',
            method: "get",
            headers: {
                'Accept':'application/json',
                'Content-Type': 'application/json'
            }        
        })
        // .then( (response)=> response.json())
        .then( (response)=> {
            if(response.user){
                current_user = response.user;
                this.setState({
                    user: current_user
                }), ()=> console.log(response);
            }
        })
    }

作为响应,我得到一个未定义的用户并且没有其他响应,并且 cookie 从未存储在我的浏览器中。但同样,如果我在 POSTMAN 中执行此操作,严格执行 POST 请求,然后执行 GET 请求,则会返回正确的用户数据,并且 cookie 也会显示在 POSTMAN 中。 关于为什么 fetch 没有将 cookie 信息传递回我的前端的任何想法?我已经尝试了两个凭据:'include' 和凭据:same-origin。

谢谢!

【问题讨论】:

    标签: javascript node.js reactjs express cookies


    【解决方案1】:

    似乎问题或至少部分问题在于您对same-origin 的使用。来自Mozilla docs斜体是我自己的):

    省略:从不发送 cookie。

    same-origin:发送用户凭据(cookies、基本 http auth 等)。如果 URL 与调用脚本同源。这是默认值。

    包括:始终发送用户凭据(cookie、基本 http 身份验证等),即使是跨域调用。

    “同源”的定义不包括different ports

    如果您将 same-origin 更改为 includefetch 应该会开始正确管理您的 cookie。

    如果不是 - 您确定 cookie “从未存储在浏览器中”吗?使用 Chrome,您可以查看chrome://settings/siteData

    【讨论】:

    • 我尝试使用include 而不是same-origin,但是当我将凭据切换到include 时,我什至没有得到输出的console.log(这很奇怪)。是的,通常我检查 chrome 的开发人员窗口并转到“应用程序”,然后转到“存储”以检查我的 cookie 是否存在——它们不在我的前端(本地主机:3000)。我也获取到 localhost:3001(我的后端)的 cookie。
    • 澄清一下:您尝试在 both 请求中将 same-origin 更改为 include?结果是第一个不抛出警报,第二个不做console.log?没有错误?
    • 啊,我一直在处理它,似乎当我将凭据设置为include 时,我确实收到一个错误 - 最初是一个 CORS 错误说明我不能使用通配符 (*) 来允许我的前端访问后端的凭据。我已经调试过了,现在我正在处理一个错误,指出:The value of the 'Access-Control-Allow-Credentials' header in the response is '' which must be 'true' when the request's credentials mode is 'include'。我目前正在尝试将允许凭据标头显式设置为 true。
    • 我不是 - 但我安装了它并让它工作。谢谢 - 修复最终是在我的 fetch 调用中将我的凭据设置为“包含”,因为它被视为 CORS 请求(同一主机的不同端口上的相同来源或跨来源的文档非常冲突)。设置之后,我必须使用 Node.js CORS 包设置更多 CORS 选项:将我的 React 前端列入白名单并启用将“Credentials”标头设置为 true。
    猜你喜欢
    • 2018-09-15
    • 2014-01-02
    • 1970-01-01
    • 2013-12-30
    • 2021-08-09
    • 2021-02-18
    • 2022-11-24
    • 2016-04-15
    • 1970-01-01
    相关资源
    最近更新 更多