Skip to content
New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

如何通过插件修改http请求的body内容 #4

Open
bugVanisher opened this issue Jan 28, 2021 · 2 comments
Open

如何通过插件修改http请求的body内容 #4

bugVanisher opened this issue Jan 28, 2021 · 2 comments

Comments

@bugVanisher
Copy link

背景

test-server插件演示了如何修改response(内容经过base64编码)内容,其中用到了client=req.request(),然后req.pipe(client)

期望

如何修改request对象本身,比如我的请求body里的json字符串用PB序列化了,正常情况下无法通过UI页面工具修改内容发起请求,而我期望在composer里面编辑json,然后想通过插件动态地把json字符串序列化为PB后请求真实服务器。需要怎么做?

@bugVanisher
Copy link
Author

bugVanisher commented Jan 28, 2021

server.on('request', (req, res) => {
    let body;
    let client;
    let data;
    req.on('data', (data) => {
      body = body ? Buffer.concat([body, data]) : data;
    });
    req.on('end', () => {
      if (body) {
        ProtoBuf.load([pb, event], function (err, root) {
          if (err)
            throw err;
          let obj = JSON.parse(body);
          let events = []
          for (const singleEvent of obj.events) {
            let bodyBytes = getBodyBytes(singleEvent.header.id, root, singleEvent.body)
            let EventMsg = root.lookupType("event.Event");
            let message = EventMsg.create({
              header: singleEvent.header,
              body: bodyBytes
            });
            events.push(message);
          }
          let EventList = root.lookupType("event.EventList");
          let eventList = EventList.create({
            events: events
          });
          data = EventList.encode(eventList).finish();
          console.log(req);
          client = req.request((svrRes) => {
            // 由于内容长度可能有变,删除长度自动改成 chunked
            delete svrRes.headers['content-length'];
            res.writeHead(svrRes.statusCode, svrRes.headers);
            let body;
            svrRes.on('data', (data) => {
              body = body ? Buffer.concat([body, data]) : data;
            });
            svrRes.on('end', () => {
              if (body) {
                res.end();
              } else {
                res.end();
              }
            });
          });
          req.pipe(client);
        });
      } else {
        res.end();
      }
    });
  });

这是我的代码,目前是监听req.on('end')获取完整请求body,但不知道如何修改这个req body

@udbmnm
Copy link

udbmnm commented Jan 18, 2022

使用reqWrite 的 hook 修改 res.end(reqBody) 就行了,reqBody是你需要请求的内容

# for free to join this conversation on GitHub. Already have an account? # to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants