在 Node.js 中发送等同于 Python 的 bytes() 的请求

Send request with equivalent to Python's bytes() in Node.js

我希望在 Node.js 中发送请求,该请求需要以字节格式发送数据。

在python中,我实现如下:

r = requests.post(url="https://example.com",headers=headers, data=bytes(exampleArray))

exampleArray的类型是uint8数组

是否可以在 Node.js 中执行相同的 post,可能使用 axios 或其他模块?

Axios 接受 variety 格式作为负载。这是一个带有 Uint8Array 数组的示例:

const axios = require('axios');

const data = new TextEncoder().encode(
  JSON.stringify({
    foo: 'bar',
  })
);

axios
  .post('http://localhost:3001', data)
  .then((res) => {
    console.log(`Status: ${res.status}`);
    console.log('Body: ', res.data);
  })
  .catch((err) => {
    console.error(err);
  });

同样适用于http(s)模块

const http = require('http');

const data = new TextEncoder().encode(
  JSON.stringify({
    foo: 'bar',
  })
);

const options = {
  hostname: 'localhost',
  port: 3001,
  path: '/',
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Content-Length': data.length,
  },
};

const req = http.request(options, (res) => {
  console.log(`statusCode: ${res.statusCode}`);

  res.on('data', (d) => {
    process.stdout.write(d);
  });
});

req.on('error', (error) => {
  console.error(error);
});

req.write(data);
req.end();