javascript - javascript中的HTTP Content-Length header 计算

标签 javascript node.js http axios coffeescript

我是 javascript 和 node-js 的新手。我在调用休息端点时遇到问题。我的问题是当我尝试使用 Postman 调用端点时一切正常。我可以在 Postman 控制台中看到计算出的 Content-Length header 。但是当我尝试在 javascript 中调用相同的端点时,出现了错误,因为计算的 Content-Length 比 Postman 计算的要低一点。这是我用来调用端点的 node.js 代码。请注意,该 API 是用于上传文件的多部分 API。

file = fs.readFileSync('/Users/.../Documents/doc.pdf')
form = new FormData()
form.append('file', file)
headers = Object.assign({'Content-Length': form.getLengthSync() }, form.getHeaders())
config = {
    method: 'post',
    url: 'https://staging:...',
    headers: headers,
    data : form
};
axios(config).then((res) ->
        console.log("The file is posted successfully. status is : " + res.status)
    ).catch((err) -> 
        console.log("The error occurred in posting file : " + err)
    )

你能告诉我这里缺少什么吗?例如,对于我正在测试的特定文件, postman 计算的值为 388,但代码将同一文件计算为 379。 注意:当我使用来自 Postman 的值对值进行硬编码时,一切正常。

最佳答案

Issue #426在表单数据存储库中似乎描述了您的问题的解决方案。

我在本地尝试了一下,并通过应用问题中描述的内容设法获得了预期的结果:

const filePath = '/Users/.../Documents/doc.pdf';
const form = new FormData();
let options = {
  knownLength: fs.statSync(filePath).size
}
form.append(
  'file',
  fs.createReadStream(filePath),
  options,
);

我认为问题与 getLengthSync specification 中的声明有关,其中指出未计算流长度,因此必须采取额外步骤才能向 FormData 实例提供正确的文件长度。

关于javascript - javascript中的HTTP Content-Length header 计算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64009931/

相关文章:

javascript - 如何在用户确认时更新 knockoutjs View 模型?

php - JavaScript/PHP : Get a Client's Month and Day with JS, 将值传递给 PHP 变量

javascript - 尝试插入数组会在 angular6 中出现错误

javascript - 如何使用nodejs和socket.io在php中实现私聊

javascript - 将流从浏览器发送到 Node JS 服务器

node.js - 在 Windows 上从命令行运行 PowerPoint 查看器

java - 我发送 7 条消息抛出 GCM 并收到 35 条消息的响应

rest - 如何设计一个查询,从中检索要以 RESTful 方式应用过滤器的资源的最后数据?

传递给不同子域的 HTTP 基本身份验证

javascript - 创建 3 个选择框(月、日、年),为每个选项创建 php 循环选项,并在 `days` 更改时使用 Javascript 更改 `months` 的选项