node.js - 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 发布。
解决方案
在Axios
, 如果存在数据,它将设置从数据计算的长度,因此即使您传递 header content-length
,它也会被代码覆盖:
查看更多详细信息: https ://github.com/axios/axios/blob/master/lib/adapters/http.js
使用http
orhttps
模块,您可以执行以下操作:
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()
推荐阅读
- java - 为什么 int 数据类型在 JAVA 中的行为是这样的?
- java - 我不明白这一系列代码的编译顺序
- google-chrome-extension - Chrome 扩展消息侦听器不起作用
- c# - c# - WPF 在没有按钮的对话框中关闭对话框
- typescript - Ag-grid cellValueChanged 样式更新
- android - 对于 OPPO 手机等少数设备,setAlarmClock() 无法在 dozo 模式下工作
- python - Pyinstaller - 加载 Python DLL 时出错 - FormatMessageW 失败
- java - 使用 Olingo / ODATA 4 编写 ExpressionVisitor 的集成测试
- regex - 正则表达式:匹配所有排列
- android - 在 Android 中读取外部 XML 文件