node.js - 如何在 Node 中使用 Axios 发布表单数据

标签 node.js axios

编辑 更改标题以便对其他人有所帮助

我正在尝试将图像上传到 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。找到答案 here
headers: 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/

相关文章:

javascript - 方法在创建的钩子(Hook) Vue.js 中不起作用

node.js - 真实 iOS 设备上的 axios、react-native、nodejs 在 Xcode 中出现网络错误?

node.js - 我无法解决的 NPM/Node 错误

javascript - Jade /哈巴狗 : Unable to use two mixins

node.js - Express错误处理中的代码质量检查与隐式next()之间的冲突

javascript - Reactjs展现动态值(value)

javascript - 如何增加/减少购物车中产品的数量?

node.js - 无论我将其添加到何处,Azure 应用程序服务( Node )CORS 源都无法工作

javascript - Node.js 返回回调中使用的变量

node.js - 我的 NodeJS 服务器在 6 个 Axios post 请求后崩溃