编辑 更改标题以便对其他人有所帮助
我正在尝试将图像上传到 imgbb使用他们的 api 使用 Axios,但不断收到错误响应 Empty upload source
.
imgbb 的 API 文档显示了以下示例:
curl --location --request POST "https://api.imgbb.com/1/upload?key=YOUR_CLIENT_API_KEY" --form "image=R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7"
我复制这个的 Node 代码是:
const fs = require('fs')
const FormData = require('form-data')
const Axios = require('axios').default
let file = '/tmp/the-test.png'
let url = 'https://api.imgbb.com/1/upload?key=myapikey'
var bodyData = new FormData();
let b = fs.readFileSync(file, {encoding: 'base64'})
bodyData.append('image', b)
Axios({
method: 'post',
url: 'url',
headers: {'Content-Type': 'multipart/form-data' },
data: {
image: bodyData
}
}).then((resolve) => {
console.log(resolve.data);
}).catch(error => console.log(error.response.data));
但我不断收到以下错误响应..
{
status_code: 400,
error: { message: 'Empty upload source.', code: 130, context: 'Exception' },
status_txt: 'Bad Request'
}
不确定我在哪里失败。
为了完成,为了他人,
--location
怎么办?标志转换为 axios 请求?
最佳答案
问题出在标题中。使用时 form-data
,你必须确保将它生成的头文件传递给 Axios。找到答案 hereheaders: bodyData.getHeaders()
工作代码是:
const fs = require('fs');
const FormData = require('form-data');
const Axios = require('axios').default;
let file = '/tmp/the-test.png';
var bodyData = new FormData();
let b = fs.readFileSync(file, { encoding: 'base64' });
bodyData.append('image', b);
Axios({
method : 'post',
url : 'https://api.imgbb.com/1/upload?key=myapikey',
headers : bodyData.getHeaders(),
data : bodyData
})
.then((resolve) => {
console.log(resolve.data);
})
.catch((error) => console.log(error.response.data));
关于node.js - 如何在 Node 中使用 Axios 发布表单数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55998715/