I wanted to recreate my python requests code in javascript for an API.
Python code:
response = requests.post("https://httpbin.org/post",data={
"test":["hello","world"]
})
print(response.text)
which returns:
{
"args": {},
"data": "",
"files": {},
"form": {
"test": [
"hello",
"world"
]
},
"headers": { "i removed"},
"json": null,
"origin": "i removed",
"url": "https://httpbin.org/post"
}
Then when I try to use npm-got to recreate the same request this happens:
const data = await got.post('https://httpbin.org/post', {
form : {"test":["hello","world"]}
})
console.log(data.body);
which returns:
{
"args": {},
"data": "",
"files": {},
"form": {
"test": "hello,world"
},
"headers": {"i removed"},
"json": null,
"origin": "i removed",
"url": "https://httpbin.org/post"
}
Why does the array turn into a string with a comma? How could I make it POST like the python request?
have you tried the KY instead that seems to match up better
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);
See https://codepen.io/ptahume/pen/poLRJKN
I hope this is of some help
try adding .json() to then end of the function call
got.post(...., { test:['hello','world']}).json()
objects and JSON are not the same in JS, need to convert the object, the npm-got library has a function to do that, or you can use js native JSON class: data = JSON.stringify({test: ['hello','world']});