【问题标题】:How to set a cookie in express after successful api requestapi请求成功后如何在express中设置cookie
【发布时间】:2016-07-06 04:31:20
【问题描述】:

因此,在我的整个应用程序中,我使用/api 路由来屏蔽我的真实 api url,并像这样以 express 方式代理它:

  // Proxy api calls
  app.use('/api', function (req, res) {
    let url = config.API_HOST + req.url // This gets my api url from config
    req.pipe(request(url)).pipe(res) // This pipes it through
  })

但是我现在需要检查当用户发布到/api/authenticate 并获得成功的响应时,我需要在 express 中使用他们的令牌设置一个 httpOnly cookie。这怎么可能实现?我还需要访问该响应返回的数据以获取令牌。

【问题讨论】:

  • @JoseHermosillaRodrigo 我相信这是其中的一部分,但如果对/api/authenticate 的发布请求的响应成功(所以代码200),我还需要设置这个cookie,所以我得到来自该响应的数据,特别是令牌并将其用作我的 cookie 的值。

标签: javascript node.js express cookies


【解决方案1】:

我不知道我是否完全理解你(而且我没有评论的声誉),但我认为你可以使用request module。示例:

var request = require('request')
//declare this inside your route if you want to send some parameters you can use formData it accepts get or post requests
request.post(config.API_HOST + req.url, formData : { field : 'something' }, function(err, response, body) {
    //here you have the response from the route with the token you generated
    //and then you can pipe this to the proxy or send the token via res
    res.send({ token : response.token }) //or use res.cookie('token', response.token)
}

有了这个你可以创建一个请求并在将数据发送到第一个响应之前将所有内容返回给你,不要忘记处理 err 参数!

【讨论】:

    猜你喜欢
    • 2016-06-05
    • 2023-03-12
    • 1970-01-01
    • 2014-10-27
    • 2018-12-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-23
    相关资源
    最近更新 更多