我如何让Axios使用FormData发送请求?

时间:2020-02-07 03:58:38

标签: node.js axios multipartform-data

使用axios时,我无法获得要调用的服务器来识别要提供的FormData。它一直告诉我,即使它在Postman和Node本机http中也无法提供正确的FormData(见下文):

import { Router } from "express";
import axios from "axios";
import * as FormData from "form-data";

const router = Router();
const cookieHeader = {
    Cookie: "XXX",
};

router.get("/", async (_req, res) => {
    try {
        const formData = new FormData();

        formData.append("key1", JSON.stringify(["value1"]));
        formData.append("key2", "value2");
        formData.append("key3", "value3");

        const response = await axios.post("https://xxx", formData, { headers: { "Content-Type": "multipart/form-data; boundary=--------------------------811161660471543283806813" } });

        res.send(response.data);
    } catch (error) {
        console.log(error);
    }
});

module.exports = router;

我能够在Postman中使用它,并使用它通过Node的本机http导出,它也可以工作:

import { Router } from "express";
import { https } from "follow-redirects";

const router = Router();

router.get("/", () => {
    const options = {
        method: "POST",
        hostname: "xxx",
        path: "/xx/xxx",
        headers: {
            "Content-Type": "multipart/form-data; boundary=--------------------------811161660471543283806813",
            Cookie: "xxx",
        },
        maxRedirects: 20,
    };

    const req = https.request(options, (res: any) => {
        const chunks: any[] = [];

        res.on("data", (chunk: any) => {
            chunks.push(chunk);
        });

        res.on("end", () => {
            const body = Buffer.concat(chunks);
            console.log(body.toString());
        });

        res.on("error", (error: any) => {
            console.error(error);
        });
    });

    const postData = `------WebKitFormBoundary7MA4YWxkTrZu0gW\nContent-Disposition: form-data; name=\"key1\"\n\n[\"value1\"]\n------WebKitFormBoundary7MA4YWxkTrZu0gW\nContent-Disposition: form-data; name=\"key2\"\n\nvalue2\n------WebKitFormBoundary7MA4YWxkTrZu0gW\nContent-Disposition: form-data; name=\"key3\"\n\nvalue3\n------WebKitFormBoundary7MA4YWxkTrZu0gW--`;

    req.setHeader("content-type", "multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW");

    req.write(postData);

    req.end();
});

module.exports = router;

2 个答案:

答案 0 :(得分:0)

在通读https://github.com/axios/axios/issues/318之后,我发现了这一点。直到快要结束时,Googrosh才发布了他使用.getHeaders()的信息。瞧,我也把它添加到了标题中,并且有效。

因此,更新我的代码,如下所示:

const response = await axios.post("https://xxx", formData, { headers: formData.getHeaders() });

答案 1 :(得分:0)

onst formUrlEncoded = x =>
   Object.keys(x).reduce((p, c) => p + `&${c}=${encodeURIComponent(x[c])}`, '')

var axios = require("axios");

axios({
  url: 'https://login.xyz.com/oauth/v2/token',
  headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
  data: formUrlEncoded({
     client_id: '***',
     client_secret: '***',
     grant_type: 'authorization_code',
  })
})
.then(function(response) {
  console.log(response.data)
})
.catch(function(error) {
  console.log(error)
})