首页 > 解决方案 > axios手动设置Content-Length,nodeJS

问题描述

有没有办法在 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 发布。

标签: node.jsaxioscontent-lengthhttp-content-length

解决方案


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

推荐阅读