简体   繁体   English

如何在NodeJ中发送多部分/表单数据PUT请求?

[英]How to send multipart/form-data PUT request in NodeJs?

I need to send an array like this: 我需要发送这样的数组:

[
  a: 'b',
  file: {file content}
]

I tried to do it using request module with formData option: 我试图使用带有formData选项的请求模块来做到这一点:

request.put({
  url: 'http://example.com/upload',
  formData: {
    a: 'b',
    file: fs.createReadStream(__dirname + '/for-test.jpg')
  }
});

In this example PUT data will be empty, it seems like formData option is ignored. 在此示例中,PUT数据将为空,似乎formData选项被忽略了。

You need to use the body attribute, and you need to stringify your object. 您需要使用body属性,并且需要对对象进行字符串化。

request({
    method: 'PUT',
    url: 'http://example.com/upload',
    body: JSON.stringify({
        a: 'b',
        file: fs.createReadStream(__dirname + '/for-test.jpg')
    })
});

I tried out your code and had the same problem. 我尝试了您的代码,并遇到了同样的问题。 After some digging i realized you are using an unreleased feature. 经过一番挖掘,我意识到您正在使用一个未发布的功能。

If you search the current npm package for the string 'formData', it doesn't exist. 如果您在当前npm软件包中搜索字符串'formData',则该字符串不存在。 If you clone the latest on github, and search that, the string 'formData' appears (I did a search using grep , btw) and there is even a test for it . 如果您在github上克隆最新版本,并进行搜索,则会出现字符串“ formData”(我使用grep ,btw进行了搜索), 甚至对此进行了测试

If you want to use this feature prerelease you can just hook up your package.json to point to the repo: 如果您想使用此功能预发行版,则只需将package.json连接起来,指向存储库即可:

{
  ...
  "dependencies": {
    ...
    "request":"git+https://github.com/request/request.git#master",
    ...
  }
} 

A fresh npm install will give you the latest from github with that feature. 全新的npm安装将为您提供来自github的最新功能。 After doing that everything was fixed for me. 完成之后,一切对我来说都是固定的。

that should hold you over until the feature is released :) 应该会拖延您,直到功能发布:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM