将curl请求转换为NodeJS请求

时间:2017-11-03 11:06:52

标签: node.js curl request

我目前正在开发一个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 ...

1 个答案:

答案 0 :(得分:1)

您的formData几乎是正确的。

但是,由于request使用form-data进行(多部分)表单处理,form-data仅支持字符串,流和值Buffer,因此您必须将对象字符串化为JSON(请参阅usage和此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'));