node.js - Posting a multipart form with file in Axios, Nodejs
问题描述
const form_data = new FormData();
form_data.append("File", fs.createReadStream(pathToFile));
form_data.append('Login', alias.toUpperCase());
const request_config = {
headers: {
"Authorization": "Basic 123",
"Content-Type": 'multipart/form-data'
},
data: form_data
};
await axios.post(url, params, request_config).then(response => {
Posting to an endpoint I can't debug. The response is a 500.
This is the error:
Is this the correct way do it?
Can I somehow see exactly what Axios is sending?
This is a postman request I received from the author of the API. This passes:
POST /api/upload HTTP/1.1
Host: api.test.contoso.se
Content-Type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW
Authorization: Basic 123
User-Agent: PostmanRuntime/7.13.0
Accept: */*
Cache-Control: no-cache
Postman-Token: 089af753-fa12-46c4-326f-dfc39c36faab,c5977145-ece3-4b53-93ff-057788eb0dcf
Host: api.test.contoso.se
accept-encoding: gzip, deflate
content-length: 18354
Connection: keep-alive
cache-control: no-cache
Content-Disposition: form-data; name="Lang"
SV
------WebKitFormBoundary7MA4YWxkTrZu0gW--
Content-Disposition: form-data; name="File"; filename="/C:/Users/file.docx
------WebKitFormBoundary7MA4YWxkTrZu0gW--
Content-Disposition: form-data; name="Login"
ABC
解决方案
屏幕截图中的错误消息很清楚:“缺少内容类型边界”。
使用 axios 进行multipart/form-data
请求,需要设置边界上传文件。示例代码是:
const form_data = new FormData();
...
const request_config = {
headers: {
"Authorization": "Basic 123",
"Content-Type": 'multipart/form-data; boundary=' + form._boundary
},
data: form_data
};
await axios.post(...)
“我能以某种方式确切地看到 Axios 发送的内容吗?”
可以使用Charles等HTTP代理软件拦截请求,查看发送了什么数据。