【问题标题】:How to write this python post request in axios?如何在 axios 中编写此 python post 请求?
【发布时间】:2022-12-17 21:36:57
【问题描述】:

我有这个用 python 编写的帖子请求,它工作得很好:

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"))),

     ] 
)

服务器应用端点写在快速API并具有以下结构:

@app.post("/test")
async def test_endpoint(
    names: List[str] = Form(...),
    surnames: List[str] = Form(...),
    references: List[UploadFile] = File(...),
    choices: List[UploadFile] = File(...)
):

我的问题是:如何使用 axios 在 Node.js 中使用此端点?

我尝试了以下内容:

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);
});

但是我遇到了 422 错误,我也尝试用 fs.readFileSync('file1.txt')formData.append("names", '["name1", "name2"]') 替换 fs.createReadStream('file1.txt'),但效果不佳。有人可以帮我解决这个问题吗?

Obs:后端应该接受可变数量的namessurnamesreferenceschoices,这就是为什么它的结构是这样的。我也在使用 axios 版本 0.21 和节点 10.19.0。

【问题讨论】:

    标签: javascript node.js axios python-requests


    【解决方案1】:

    const axios = require("axios");
    const fs = require("fs");
    
    const response = axios.request({
      method: "POST",
      url: "http://localhost:8086/parse",
      data: {
        names: ["name1", "name2"],
        surnames: ["surname1", "surname2"]
      },
      files: [
        {
          name: "choices",
          filename: "choices-1",
          file: fs.createReadStream("file1.txt")
        },
        {
          name: "choices",
          filename: "choices-2",
          file: fs.createReadStream("file2.txt")
        },
        {
          name: "references",
          filename: "references-1",
          file: fs.createReadStream("file3.txt")
        },
        {
          name: "references",
          filename: "references-2",
          file: fs.createReadStream("file4.txt")
        }
      ]
    });
    
    console.log(response.data);

    【讨论】:

      猜你喜欢
      • 2021-04-02
      • 2021-01-25
      • 2020-11-07
      • 2019-10-10
      • 2017-12-08
      • 2016-10-01
      • 2019-07-23
      • 2021-08-02
      • 2022-01-02
      相关资源
      最近更新 更多