Axios手动设置Content-Length,nodeJS [英] Axios set Content-Length manually, nodeJS

查看:1969
本文介绍了Axios手动设置Content-Length,nodeJS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在nodeJS中发送发布请求并指定内容长度.

Is there a way to send a post request in nodeJS and specify th content-length.

我尝试过(使用axios):

I tried (using 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);

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

It doesn't work, the length is set automatically to a value other then the one I pass.

我正在使用axios,但愿意使用任何其他方式从nodeJS进行发布.

I am using axios but open to using any other way to post from nodeJS.

推荐答案

Axios中,如果存在数据,它将设置从数据计算得出的长度,因此即使传递标头content-length,也会被代码覆盖:

In Axios, If data is present it will set length calculated from data, so even if you pass header content-length, it will be overridden by code:

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

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

Using http or https module you can do:

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

这篇关于Axios手动设置Content-Length,nodeJS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆