I have this post request written in python, which works just fine:
import requests
requests.request(
"POST",
"http://locahost:8086/parse",
data={
"names": ["name1", "name2"],
"surnames": ["surname1", "surname2"]
},
files=[
("choices", ("choices-1", open("file1.txt", "rb"))),
("choices", ("choices-2", open("file2.txt", "rb"))),
("references", ("references-1", open("file3.txt", "rb"))),
("references", ("references-2", open("file4.txt", "rb"))),
]
)
The server application endpoint is written in fastapi and has the following structure:
@app.post("/test")
async def test_endpoint(
names: List[str] = Form(...),
surnames: List[str] = Form(...),
references: List[UploadFile] = File(...),
choices: List[UploadFile] = File(...)
):
My question is: How can I consume this endpoint in Node.js using axios?
I tried with the following:
const axios = require("axios");
const fs = require("fs");
const FormData = require("form-data");
const formData = new FormData();
formData.append("names", "name1");
formData.append("names", "name2");
formData.append("surnames", "surname1");
formData.append("surnames", "surname2");
formData.append("references", fs.createReadStream('file1.txt'));
formData.append("references", fs.createReadStream('file2.txt'));
formData.append("choices", fs.createReadStream('file3.txt'));
formData.append("choices", fs.createReadStream('file4.txt'));
axios.post("http://localhost:8086/parse", formData).then(response => {
console.log(response.data);
}).catch(err => {
console.log(err);
});
But I've got the 422 error, I also tried to replace the fs.createReadStream('file1.txt')
with fs.readFileSync('file1.txt')
and formData.append("names", '["name1", "name2"]')
but it did not work as well. Can someone help me out to make this post work?
Obs: The backend should accept a variable number of names
, surnames
, references
and choices
, that is why it is structured like this. I am also using the axios version 0.21 and node 10.19.0.