【问题标题】:Send request with equivalent to Python's bytes() in Node.js在 Node.js 中发送等效于 Python 的 bytes() 的请求
【发布时间】:2021-12-30 15:41:54
【问题描述】:

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

在python中,我实现了如下:

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

exampleArray的类型为uint8数组

是否可以在 Node.js 中使用 axios 或其他模块来做同样的文章?

【问题讨论】:

    标签: node.js axios request byte


    【解决方案1】:

    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();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-03-27
      • 1970-01-01
      • 1970-01-01
      • 2016-12-15
      • 1970-01-01
      • 2014-07-01
      • 1970-01-01
      • 2021-08-18
      相关资源
      最近更新 更多