【问题标题】:Send a set-cookie header to a redirect url in node.js将 set-cookie 标头发送到 node.js 中的重定向 url
【发布时间】:2016-10-11 05:00:16
【问题描述】:

我正在使用 node.js request 模块从 API 获取 id_token。获取该 id_token 后,我想发送带有set-cookie header to the redirected urlredirect uri 响应。但我不知道该怎么做。

这是我的代码:

app.use("/nodejs-server/retrieveCode", function(req, res) {

        var clientID = 'some random string'
        var client_Secret = 'another random string'
        var code_token = clientID + ":" + client_Secret
        var buffer = new Buffer(code_token)
        var token = buffer.toString('base64')
        var rtoken = "Basic " + token;
        var headers = {
            'Content-Type': 'application/json',
            'Authorization': rtoken
        }
        var postData = {grant_type: 'authorization_code', code: req.query.code, redirect_uri: 'http://localhost:3000/nodejs-server/retrieveCode'} //Query string data
        var options  = {
            method: 'POST', //Specify the method
            body: postData,
            url: 'http://localhost:4000/server/token',
            json: true,
            headers: headers
        }
        request(options
        , function(error, response, body){
            if(error) {
                console.log(error);
            } else {
                //send a redirect uri and set-cookie header response

            }
        });

我尝试过使用

res.redirect(302, "http://localhost:9000");

它可以重定向,但我也不能用它发送 cookie

感谢任何帮助。

【问题讨论】:

    标签: javascript node.js express redirect cookies


    【解决方案1】:

    经过大量的试验和错误以及谷歌搜索,我终于能够实现我的目标。为了向重定向 URL 发送一个过期的 cookie,我刚刚添加了

    const expires = body.exp.toUTCString();
    res.cookie('id_token', body.id_token, { expires });
    res.redirect(302, 'http://localhost:8080');
    

    【讨论】:

    • 请注意,不需要 302,因为 Express 已将 302 设为默认状态码。
    • 没有快递你会怎么做?
    【解决方案2】:

    在 express 4.16.3 中,你必须设置

    res.cookie()

    之前

    res.redirect()

    它对我有用,没有错误

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-03-05
      • 2022-09-28
      • 2021-03-20
      • 2013-02-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多