【问题标题】:Convert a curl request into NodeJS request将 curl 请求转换为 NodeJS 请求
【发布时间】:2018-04-16 02:22:33
【问题描述】:

我目前正在开发一个 API,它提供了一个 curl 请求示例,如下所示:

curl -v -H "Accept-Token: mysecret" -H "User-Token: my_user" \
     -F "filename=@my_photo.jpg" \
     -F "face_detection={\"fast\" : true}" \
     -F "age_detection={\"something\" : true}" \
     127.0.0.1:8080/vision_batch

当我提出这样的请求时,这就是打印 netcat 的内容:

POST /vision_batch HTTP/1.1
Host: 127.0.0.1:9000
User-Agent: curl/7.47.0
Accept: */*
Accept-Token: test_token
User-Token: test
Content-Length: 635202
Expect: 100-continue
Content-Type: multipart/form-data; boundary=------------------------a32bed4123bace7d

--------------------------a32bed4123bace7d
Content-Disposition: form-data; name="filename"; filename="photo.png"
Content-Type: application/octet-stream
<binary_content>
--------------------------a32bed4123bace7d
Content-Disposition: form-data; name="face_detection"

{}
--------------------------a32bed4123bace7d
Content-Disposition: form-data; name="qr_recognition"

{}
--------------------------a32bed4123bace7d--

但我不知道如何在 NodeJS 中翻译这种多种形式。我目前正在为每个表单执行多个请求,但我每次都必须发送图像......

这是我当前的代码:

function getOptions(buffer, service) {
  return {
    url: 'http://127.0.0.1:9001/' + service,
    headers: headers,
    method: 'POST',
    formData: {
      filename: buffer,
      face_recognition: [],
      age_detection: []
    }
  }
}

var res_json = {};
request(getOptions(buffer, 'face_recognition'), function(error, response, body) {
});

问题是 API 返回了我no args。实际上,netcat 正在打印以下内容:

POST /vision_batch HTTP/1.1
Accept-Token: YE6geenfzrFiT88O
User-Token: ericsson_event
host: 127.0.0.1:9000
content-type: multipart/form-data; boundary=--------------------------648089449032824937983411
content-length: 663146
Connection: close

----------------------------648089449032824937983411
Content-Disposition: form-data; name="filename"
Content-Type: application/octet-stream
<binary_content>
----------------------------648089449032824937983411--

问题是我不怎么改变请求中的formData字段...

【问题讨论】:

    标签: node.js curl request


    【解决方案1】:

    您的formData 几乎是正确的。

    但是,由于request 使用form-data 进行(多部分)表单处理,而form-data 仅支持字符串、流和Buffers 值,因此您必须将对象字符串化为JSON(请参阅@ 987654323@ 和这个issue)。

    这将完全复制您的 curl 请求(假设之前填充了 headersbuffer):

    function getOptions(buffer, service) {
      return {
        url: 'http://127.0.0.1:9001/' + service,
        headers: headers,
        method: 'POST',
        formData: {
          filename: buffer,
          face_recognition: JSON.stringify({fast: true}),
          age_detection: JSON.stringify({something: true})
        }
      }
    }
    request(getOptions(buffer, 'face_recognition'));
    

    【讨论】:

      猜你喜欢
      • 2017-10-17
      • 2021-02-06
      • 2017-01-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-10
      • 2023-04-02
      相关资源
      最近更新 更多