【问题标题】:What am I doing wrong when trying to set a cookie using Express尝试使用 Express 设置 cookie 时我做错了什么
【发布时间】:2020-05-31 11:18:34
【问题描述】:

我目前正在尝试在登录后将 cookie 发送回我的 react 应用程序, 在我的服务器中,我有一个测试响应:

res.status(200).cookie('nameOfCookie', 'cookieValue', { maxAge: 1000* 60 * 60 }).end();

在我的应用程序中

Axios.post('http://localhost:5000/User/login', userDetails).then(res => {
    console.log(JSON.stringify(res))
    this.props.history.push('/list');
})

通过调用收到响应,

{"data":"","status":200,"statusText":"OK","headers":{"content-length":"0"},"config":{"url": "http://localhost:5000/User/login","method":"post","data":"{\"email\":\"a\",\"password\":\"a\"}","headers": {"接受":"应用程序/json, 文本/纯文本, /","Content-Type":"application/json;charset=utf-8"},"transformRequest":[null],"transformResponse":[null],"timeout":0 ,"xsrfCookieName":"XSRF-TOKEN","xsrfHeaderName":"X-XSRF-TOKEN","maxContentLength":-1},"request":{}}

但是最终没有设置 cookie,有人可以告诉我这里的问题是什么吗? 谢谢-

我也有

app.use(cookieParser());

作为第一个应用程序使用,这是推荐的,但这没有帮助

【问题讨论】:

    标签: javascript node.js reactjs express cookies


    【解决方案1】:

    我终于明白了:

    事实证明,Axios 默认将 'withCredentials' 设置为 false,所以我创建了一个带有覆盖的新实例并改用它

    var myAxios = Axios.create ({
        withCredentials: true
    })
    

    这还要求我更新 cors 以接受这些凭据

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

    【讨论】:

      【解决方案2】:

      react 应用程序无法设置 cookie,因为后端应用程序在不同的端口上运行,所以这是跨域 cookie 问题。

      您必须在后端设置以下标头,并在Axios 请求中设置withCredentials: true

      凭据: 您要用于请求的请求凭据:omitsame-origininclude。要自动发送当前域的 cookie,必须提供此选项。从 Chrome 50 开始。

      在 Axios 中

      withCredentials 表示是否应使用凭据进行跨站点访问控制请求默认值:withCredentials:false。

      1. "Access-Control-Allow-Origin: http://localhost:3000";
      2. "Access-Control-Allow-Credentials: true";
      3. "Access-Control-Allow-Methods: GET, POST";
      4. "Access-Control-Allow-Headers: Content-Type, *";
      

      示例:

      res
        .set("Access-Control-Allow-Origin", "http://localhost:3000")
        .set("Access-Control-Allow-Credentials", "true")
        .set("Access-Control-Allow-Methods", "GET, POST")
        .set("Access-Control-Allow-Headers", "Content-Type, *")
        .status(200).cookie('nameOfCookie', 'cookieValue', { maxAge: 1000 * 60 * 60 }).end();
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-06-22
        • 1970-01-01
        • 1970-01-01
        • 2011-06-13
        • 2020-08-07
        • 2018-10-16
        • 1970-01-01
        相关资源
        最近更新 更多