SurgeTeam
您可能没有理解我的想法,binary-body-mode 确实可以在 http-request ,http-response 中获取 binary body,但是$httpClient 发送请求时出现了问题。我简单列一下代码,这样可能更方便您清楚我的意图。
脚本配置文件
Demo = type=http-request,pattern=URL,requires-body=1,max-size=-1,binary-body-mode=1,script-path=Demo.js
脚本内容截取
// 获取 request binary body
var binaryBody = $request.body;
var msg = Request.fromBinary(binaryBody); //转成 object
/**
* 做一些修改
*/
$request.body = Request.toBinary(msg) //转回 binary
console.log($request.body instanceof Uint8Array) // true
console.log($request.headers) // {"accept":"*\/*","content-type":"application\/x-protobuf"... } 这里 content-type 为protobuf
// 重新发送修改后的请求
$httpClient.post($request, (error, response, data) => {
console.log(typeof data) // string
/**
* 做一些修改
*/
$done({ response: { body: data } })
}
因为 surge 目前不支持同时修改request 和response,所以需要使用$httpClient 手动发送一次请求,并将请求结果返回到客户端。
问题
1、使用 $httpClient.post
发送的请求,headers 中的content-type 被强制覆盖成了 application/json
, request.body 也从 binary 转成了 object,这导致了请求失败。
2、$httpClient.post
返回的 data 为 string 而不是 binary,这里应该可以用 new TextEncoder().encode
做一个转换,直接给一个 raw 类型直接获取可能会更方便一点。