1

有没有办法在 nodeJS 中发送发布请求并指定内容长度。

我试过(使用 axios):

let data = `Some text data...........`;

let form = await Axios.post(
    "url.......",
    data,
    {
        headers: {
            Authentication: "token.....",
            "Content-Type": "multipart/form-data; boundary=c9236fb18bed42c49590f58f8cc327e3",
            //set content-length manually 
            "Content-Length": "268"
        }
    }
).catch(e => e);

它不起作用,长度会自动设置为我通过的值以外的值。

我正在使用 axios,但可以使用任何其他方式从 nodeJS 发布。

4

2 回答 2

3

Axios, 如果存在数据,它将设置从数据计算的长度,因此即使您传递 header content-length,它也会被代码覆盖: 在此处输入图像描述

查看更多详细信息: https ://github.com/axios/axios/blob/master/lib/adapters/http.js

使用httporhttps模块,您可以执行以下操作:

const https = require('https')

const data = JSON.stringify({
  key:values
})

const options = {
  hostname: 'example.com',
  port: 443,
  path: '/testpath',
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Content-Length': data.length
  }
}
const req = https.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()
于 2020-01-28T18:57:29.537 回答
2

由于声誉低下,我无法添加评论,但 Sandeep Patel 的部分回答Axios已经过时。您可以Content-Length手动设置。如果存在标头,则Axios不会覆盖:Content-Lengthcontent-length

// Add Content-Length header if data exists
  if (!headerNames['content-length']) {
    headers['Content-Length'] = data.length;
  }

来源:https ://github.com/axios/axios/blob/master/lib/adapters/http.js#L108

因此,在您的情况下,它将是:

let data = `Some text data...`;

let form = await Axios.post(
    "url...",
    data,
    {
        headers: {
            Authentication: "token....",
            "Content-Type": "contentType...",
            //set content-length manually 
            "Content-Length": "268",
            "content-length": "268"
        }
    }
).catch(e => e);
于 2022-03-01T10:48:16.360 回答