【问题标题】:proxyReq.setHeader can not set headers after they are sentproxyReq.setHeader 发送后不能设置 headers
【发布时间】:2018-10-06 23:20:35
【问题描述】:

我正在构建一个 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

【问题讨论】:

标签: node.js node-http-proxy


【解决方案1】:

让 check_ip 返回一个 promise 并尝试

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

【讨论】:

  • 我该如何消费承诺
  • 在 pAny 函数的 then 中。结果将满足第一个承诺。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-21
  • 2015-09-28
  • 2012-03-04
  • 1970-01-01
  • 2013-04-06
  • 2017-09-23
相关资源
最近更新 更多