proxyReq.setHeader发送后无法设置标头

时间:2018-10-06 23:20:35

标签: node.js node-http-proxy

我正在构建一个node.js代理,我想添加一个条件标头

proxy.on('proxyReq', (proxyReq, req, res) => {

        const realIP =  parseHttpHeader(req.headers['x-real-ip'])[0];
      const path = parseHttpHeader(req.headers['x-original-uri'])[0];
        pAny([
                check_ip(realIP) ,
                check_path(path) ,
                check_geo(realIP)
        ]).then(result => {
                console.log (result , "result " )
                if (result) {
                proxyReq.setHeader('namespace' , 'foo');    
                } else {
                proxyReq.setHeader('namespace' , 'bar');    }
                        console.log('sending req ')
        });

});

async function check_ip(realIP) { 
    try {
            const result = await ipModel.findOne({ip: realIP}).exec()
            console.log(realIP , result , "ip")
            if (result) {
                return true
            } else {
                return false
            }
    } catch (e) {
        throw e;
    }
}

它可以正常工作,直到我使用方法check_ip然后出现错误

(node:3793) UnhandledPromiseRejectionWarning: Error: Can't set headers after they are sent.
at validateHeader (_http_outgoing.js:491:11)
at ClientRequest.setHeader (_http_outgoing.js:498:3)
at /home/master/IPS/server.js:109:14
at <anonymous>
at process._tickCallback (internal/process/next_tick.js:189:7)
(node:3793) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:3793) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

该错误清楚地表明我以错误的方式处理了诺言,但我不知道如何解决它,我尝试使用callbacks尝试使用await

1 个答案:

答案 0 :(得分:0)

使check_ip返回承诺并尝试

function check_ip(realIP) {
  return ipModel.findOne({ ip: realIP }).exec();
}