如何在 api 请求成功后在快递中设置 cookie

How to set a cookie in express after successful api request

本文关键字:快递 设置 cookie 成功 api 请求      更新时间:2023-09-26

所以在我的整个应用程序中,我正在使用/api路由来屏蔽我的真实 api url,我像这样快速代理它:

  // 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并获得成功的响应时,我是否需要在快递内使用他们的令牌设置 httpOnly cookie。如何实现这一点?我还需要访问该响应返回的数据才能获取令牌。

我不知道

我是否完全理解了你(而且我没有声誉可以评论),但我认为您可以使用请求模块。例:

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 参数!