Nodejs请求流 - 在响应管道之前操纵cookie

时间:2015-11-22 12:56:58

标签: javascript node.js cookies stream

我有一个Express代理,它使用请求NPM模块对远程服务器进行CRUD调用。在响应上,我做cookie操作来改变路径。这是这里的代码。

    request({
        method: req.method,
        url: proxyUrl,
        jar: jar,
        headers: headers,
        json: jsonBody,
    }, function(error, response, body) {

        if (error && response.statusCode !== 201 || response.statusCode !== 200) {
            logger.info("proxying failed - reason: " + error);
            return res.status(response.statusCode).send(body);
        };
        var cookies = jar.getCookies(proxyUrl);
        for (var i = 0; i < cookies.length; i++) {
            var cookie = cookies[i];
            if (cookie.path !== "/") {
                cookie.path = "/"; //change path from /api to /
                cookie.secure = (os.hostname().indexOf("local") > -1 ? false : true);
            }
            res.cookie(cookie);
        };
        res.headers = response.headers;
        return res.status(response.statusCode).send(body);
    });

这很好用。 但现在,NodeJs带有流。所以,我编写这段代码来实现与nodejs流相同的。

    req.pipe(
        request({
            method:req.method,
            url: proxyUrl,
            jar: jar,
            json:req.body

        })).on("response", function(response) {
        var cookies = jar.getCookies(proxyUrl);
        console.log(cookies);
        if (response.statusCode === 201 || response.statusCode === 200 || response.statusCode === 202) {
            logger.info("successfully proxied");

            for (var i = 0; i < cookies.length; i++) {
                var cookie = cookies[i];
                if (cookie.path !== "/") {
                    cookie.path = "/"; //change path from /api to /
                    cookie.secure = (os.hostname().indexOf("local") > -1 ? false : true);
                }
                jar.setCookie(cookie, proxyUrl);
            }
        } else {
            logger.info("proxying failed - reason: " + error || "refer body");
        }
    }).pipe(res)

这不会改变cookie路径。 请求实现tough.cookie。所以,如果我对cookie jar进行了规划,它会存储在请求的响应中,因此不应该一直用它来管理表达的响应吗?

0 个答案:

没有答案