2016-07-05 36 views
0

所以橫跨整個我的應用我使用/api途徑來掩蓋我真正的API網址和我的代理其在快遞這樣的:現在如何設置明確一個cookie成功的API請求後

// 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與他們的令牌從明文內。這怎麼可能實現?我還需要訪問該響應返回的數據來獲取令牌。

+0

您是否在尋找http://expressjs.com/zh/4x/api.html#res.cookie? –

+0

@JoseHermosillaRodrigo我相信這是它的一部分,但如果從'/ api/authenticate'的發佈請求響應成功(所以代碼200),我還需要設置這個cookie,因此我從該響應中獲取數據,具體表示並將其用作我的Cookie的值。 – Ilja

回答

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) 
} 

有了這個,你可以創建一個請求,並擁有一切的數據發送到第一反應之前還給你,不要忘記處理犯錯的說法!