繁体   English   中英

为什么使用表单时 npm-got 中的 POST 不能正确发送数组?

[英]Why isn't the POST in npm-got sending arrays properly when using form?

我想在 javascript 中为 API 重新创建我的 python 请求代码。

Python代码:

response = requests.post("https://httpbin.org/post",data={
    "test":["hello","world"]
})

print(response.text)

返回:

{
  "args": {},
  "data": "",
  "files": {},
  "form": {
    "test": [
      "hello",
      "world"
    ]
  },
  "headers": { "i removed"},
  "json": null,
  "origin": "i removed",
  "url": "https://httpbin.org/post"
}

然后,当我尝试使用 npm-got 重新创建相同的请求时,会发生这种情况:

const data = await got.post('https://httpbin.org/post', {
    form : {"test":["hello","world"]}
})

console.log(data.body);

返回:

{
  "args": {}, 
  "data": "", 
  "files": {}, 
  "form": {
    "test": "hello,world"
  }, 
  "headers": {"i removed"}, 
  "json": null, 
  "origin": "i removed", 
  "url": "https://httpbin.org/post"
}

为什么数组变成带逗号的字符串? 我怎样才能让它像 python 请求一样发布?

您是否尝试过似乎更匹配的KY

import ky from 'https://cdn.skypack.dev/ky?dts';

const formData = new FormData();
formData.append('test', 'hello');
formData.append('test', 'world');
const response = await ky.post("https://httpbin.org/anything", {body: formData}).json();
console.log(response);

https://codepen.io/ptahume/pen/poLRJKN

我希望这会有所帮助

尝试将 .json() 添加到函数调用的末尾

got.post(...., { test:['hello','world']}).json()

JS中的objects和json不一样,需要对object进行转换,npm-got库有函数可以做到,也可以使用js原生的json类: data = JSON.stringify({test: ['hello','world']});

暂无
暂无

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

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