最新消息: 电脑我帮您提供丰富的电脑知识,编程学习,软件下载,win7系统下载。

node http

IT培训 admin 6浏览 0评论

node http

我需要异步修改请求体。有点像这样:

proxy.on('proxyReq', function(proxyReq, req, res, options) {
  if(req.body) {
    new Promise(function(resolve){ 
      setTimeout(function() { // wait for the db to return
        'use strict';
        req.body.text += 'test';
        let bodyData = JSON.stringify(req.body);
        proxyReq.setHeader('Content-Type','application/json');
        proxyReq.setHeader('Content-Length', Buffer.byteLength(bodyData));
        // stream the content
        proxyReq.write(bodyData);
        resolve();
      },1);
    });
  }
});

当我运行这个时,我得到的错误是,一旦设置了标题就无法修改标题。这是有道理的。

在我准备好之前,如何停止发送请求?我已经看过从proxyReq中删除各种监听器但没有成功..

回答如下:

通过查看source code @ - ),似乎不太可能,因为发送了proxyReq事件,然后代码继续运行。

如果它会等待承诺,那么就有可能(如果你也回复了这个承诺)。

这个lib上的最小分叉可以是例如:

// Enable developers to modify the proxyReq before headers are sent
proxyReq.on('socket', function(socket) {
  if(server) { server.emit('proxyReq', proxyReq, req, res, options); }
});

(proxyReq.proxyWait || Promise.resolve())
    .then( ... // rest of the code inside the callback 

接着

proxy.on('proxyReq', function(proxyReq, req, res, options) {
  if(req.body) {
    proxyReq.proxyWait = new Promise(function(resolve){ 
      setTimeout(function() { ...

但根据您的使用情况,可能还有其他解决方案。例如,考虑是否确实需要使用此代理库。你也可以直接使用http,你可以对事件和回调进行全面控制。

node http

我需要异步修改请求体。有点像这样:

proxy.on('proxyReq', function(proxyReq, req, res, options) {
  if(req.body) {
    new Promise(function(resolve){ 
      setTimeout(function() { // wait for the db to return
        'use strict';
        req.body.text += 'test';
        let bodyData = JSON.stringify(req.body);
        proxyReq.setHeader('Content-Type','application/json');
        proxyReq.setHeader('Content-Length', Buffer.byteLength(bodyData));
        // stream the content
        proxyReq.write(bodyData);
        resolve();
      },1);
    });
  }
});

当我运行这个时,我得到的错误是,一旦设置了标题就无法修改标题。这是有道理的。

在我准备好之前,如何停止发送请求?我已经看过从proxyReq中删除各种监听器但没有成功..

回答如下:

通过查看source code @ - ),似乎不太可能,因为发送了proxyReq事件,然后代码继续运行。

如果它会等待承诺,那么就有可能(如果你也回复了这个承诺)。

这个lib上的最小分叉可以是例如:

// Enable developers to modify the proxyReq before headers are sent
proxyReq.on('socket', function(socket) {
  if(server) { server.emit('proxyReq', proxyReq, req, res, options); }
});

(proxyReq.proxyWait || Promise.resolve())
    .then( ... // rest of the code inside the callback 

接着

proxy.on('proxyReq', function(proxyReq, req, res, options) {
  if(req.body) {
    proxyReq.proxyWait = new Promise(function(resolve){ 
      setTimeout(function() { ...

但根据您的使用情况,可能还有其他解决方案。例如,考虑是否确实需要使用此代理库。你也可以直接使用http,你可以对事件和回调进行全面控制。

与本文相关的文章

发布评论

评论列表 (0)

  1. 暂无评论