如何在节点中使用Axios发布表单数据 [英] How to post form data using Axios in node

查看:51
本文介绍了如何在节点中使用Axios发布表单数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

EDIT (更改标题),以便对他人有帮助

EDIT Changing the title so that it might be helpful to others

我正尝试使用Axios的api将图像上传到 imgbb 响应空上传源.

I am trying to upload an image to imgbb using their api using Axios, but keep getting an error response Empty upload source.

imgbb的API文档显示了以下示例:

The API docs for imgbb shows the following example:

curl --location --request POST "https://api.imgbb.com/1/upload?key=YOUR_CLIENT_API_KEY" --form "image=R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7"

我要复制的节点代码是:

My node code to replicate this is:

    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));

但是我不断收到以下错误响应.

But I keep getting the following error response..

{
status_code: 400,
error: { message: 'Empty upload source.', code: 130, context: 'Exception' },
status_txt: 'Bad Request'
}

不确定确切的位置.

出于完成及其他目的,-location 标志如何转换为axios请求?

For the sake of completion and for others, how does the --location flag translate to an axios request?

推荐答案

问题出在标题中.使用 form-data 时,必须确保将其生成的标头传递给Axios.在此处

The issue was in the headers. When using form-data, you have to make sure to pass the headers generated by it to Axios. Answer was found here

标头: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));

这篇关于如何在节点中使用Axios发布表单数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆