gpt4 book ai didi

node.js - 如何让 Axios 使用 FormData 发送请求?

转载 作者:行者123 更新时间:2023-12-04 10:37:15 37 4
gpt4 key购买 nike

当我使用 axios 时,我无法让我调用的服务器识别我提供的 FormData。它一直告诉我我没有提供正确的 FormData,即使它在 Postman 和 Node native http 中工作(见下文):

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 的 native 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;

最佳答案

看完https://github.com/axios/axios/issues/318我明白了.直到快结束时,Googrosh 才发帖说他使用了 .getHeaders()。瞧,我也将它添加到我的标题中并且它起作用了。

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

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

关于node.js - 如何让 Axios 使用 FormData 发送请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60106888/

37 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com