Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

如何才能通过脚本自定义修改响应体? #19

Open
ibearye opened this issue Mar 26, 2022 · 3 comments
Open

如何才能通过脚本自定义修改响应体? #19

ibearye opened this issue Mar 26, 2022 · 3 comments

Comments

@ibearye
Copy link

ibearye commented Mar 26, 2022

根据示例,请求回来的结果是空的,而不是"hello, world!"

exports.handleRequest = (ctx, request) => {
	// ctx.fullUrl 可以获取请求url
	// ctx.headers 可以获取请求头
	// ctx.options 里面包含一些特殊的请求头字段,分别可以获取一些额外信息,如请设置的规则等
	// ctx.method 获取和设置请求方法
	// ctx.req
	// ctx.res
  const {req, res} = ctx;
  const client = 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', () => {
      res.end(Buffer.from('hello, world!'));
    });
  });
  req.pipe(client);
};
@avwo
Copy link
Member

avwo commented Mar 26, 2022

  1. 优先使用 Whistle 内置协议:https://wproxy.org/whistle/rules/rule/ https://wproxy.org/whistle/rules/resBody.html
  2. whistle.script 修改响应内容,可以先了解操作 Node Stream 相关知识

@ibearye
Copy link
Author

ibearye commented Mar 27, 2022

根据stream的操作,我感觉代码应该没什么问题,下面的代码:

exports.handleRequest = (ctx, request) => {
  const {req, res} = ctx;
  const client = req.request((svrRes) => {
    // 由于内容长度可能有变,删除长度自动改成 chunked
    delete svrRes.headers['content-length'];
    res.writeHead(svrRes.statusCode, svrRes.headers);
    res.write('hello');
    res.end();
  });
  req.pipe(client);
};

打开devtools看请求,结果就是请求一直未完成

image

image

@ibearye
Copy link
Author

ibearye commented Mar 27, 2022

问题已解决,发现是数据编码的问题,把请求头的accept-encoding去除即可

delete req.headers['accept-encoding'];

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

No branches or pull requests

2 participants