我在工作过程中用到了request模块来模拟前端请求进行接口测试,但是在测试buffer的时候遇到了问题,卡了很久,查阅了大量的资料才发现是个由底层逻辑触发的乌龙。因此记录下来并分享给各位。
首先引入request模块(假设你已有NodeJS):
npm install -s request
同时你需要一个后端,可以使用express-generator生成,参考https://blog.youkuaiyun.com/Z_ammo/article/details/103559758
设置接口:
app = express();
app.post('/', function(req, res, next) {
console.log(req.headers);
let buf = [];
req.on('data', (data) => {
buf.push(data);
});
req.on('end', () => {
buf = Buffer.concat(buf);
console.log(buf.toString());
});
res.send('1');
});
现在发送请求:
var formData = {
my_field: 'my_value',
my_buffer: Buffer.from([1,2,3]) // 这里我使用了request官方的示例,也就是坑爹的开始
};
//post请求
reque