0

i am building a node.js proxy and i want to add a conditional header

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

and it works just fine till i use the methos check_ip then i get the error

(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.

as the error clearly states i am handeling a promise in the wrong way but i don't know how to fix it i tried using callbacks i tried using await

1 Answers1

0

make the check_ip return a promise and try

function check_ip(realIP) {
  return ipModel.findOne({ ip: realIP }).exec();
}
Tarek Essam
  • 3,602
  • 2
  • 12
  • 21