Axios手动设置Content-Length,nodeJS [英] Axios set Content-Length manually, 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
使用http
或https
模块,您可以执行以下操作:
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屋!