Reactjs axios发送表单数据的post请求

Reactjs axios发送表单数据的post请求,reactjs,react-redux,axios,ajaxform,axios-cookiejar-support,Reactjs,React Redux,Axios,Ajaxform,Axios Cookiejar Support,axiosPOSTrequest正在点击控制器上的url,但将null值设置为我的POJO类,当我在chrome中浏览开发工具时,有效负载包含数据。我做错了什么 Axios POST请求: var body = { userName: 'Fred', userEmail: 'Flintstone@gmail.com' } axios({ method: 'post', url: '/addUser', data: body }) .then(functi

axios
POST
request正在点击控制器上的url,但将null值设置为我的POJO类,当我在chrome中浏览开发工具时,有效负载包含数据。我做错了什么

Axios POST请求:

var body = {
    userName: 'Fred',
    userEmail: 'Flintstone@gmail.com'
}

axios({
    method: 'post',
    url: '/addUser',
    data: body
})
.then(function (response) {
    console.log(response);
})
.catch(function (error) {
    console.log(error);
});
<input type="file" id="image" accept="image/png"/>
const formData = new FormData()

// add a non-binary file
formData.append('files[]', new Blob(['{"hello": "world"}'], { type: 'application/json' }), 'request.json')

// add a binary file
const element = document.getElementById('image')
const file = element.files[0]
formData.append('files[]', file, file.name)
await rc.post('/restapi/v1.0/account/~/extension/~/fax', formData)
浏览器响应:

var body = {
    userName: 'Fred',
    userEmail: 'Flintstone@gmail.com'
}

axios({
    method: 'post',
    url: '/addUser',
    data: body
})
.then(function (response) {
    console.log(response);
})
.catch(function (error) {
    console.log(error);
});
<input type="file" id="image" accept="image/png"/>
const formData = new FormData()

// add a non-binary file
formData.append('files[]', new Blob(['{"hello": "world"}'], { type: 'application/json' }), 'request.json')

// add a binary file
const element = document.getElementById('image')
const file = element.files[0]
formData.append('files[]', file, file.name)
await rc.post('/restapi/v1.0/account/~/extension/~/fax', formData)

如果我将标题设置为:

headers:{
  Content-Type:'multipart/form-data'
}
请求抛出错误

过帐多部分/表单数据时出错。内容类型标头缺少边界

如果我在postman中发出相同的请求,它工作正常,并为我的POJO类设置值


任何人都可以解释如何设置边界,或者我如何使用axios发送表单数据。

您可以使用如下方式发布axios数据:

var bodyFormData=new FormData();
然后将字段添加到要发送的表单中:

bodyFormData.append('userName','Fred');
如果您正在上载图像,可能需要使用
.append

bodyFormData.append('image',imageFile);
然后您可以使用axios post方法(您可以相应地修改它)

axios({
方法:“张贴”,
url:“我的url”,
数据:bodyFormData,
标题:{“内容类型”:“多部分/表单数据”},
})
.然后(功能(响应){
//成功
控制台日志(响应);
})
.catch(函数(响应){
//处理错误
控制台日志(响应);
});
相关GitHub问题:

上传(多个)二进制文件 Node.js 当您想通过
多部分/表单数据发布文件时,事情会变得复杂,尤其是多个二进制文件。下面是一个工作示例:

const FormData = require('form-data')
const fs = require('fs')
const path = require('path')

const formData = new FormData()
formData.append('files[]', JSON.stringify({ to: [{ phoneNumber: process.env.RINGCENTRAL_RECEIVER }] }), 'test.json')
formData.append('files[]', fs.createReadStream(path.join(__dirname, 'test.png')), 'test.png')
await rc.post('/restapi/v1.0/account/~/extension/~/fax', formData, {
  headers: formData.getHeaders()
})
  • 我更喜欢
    headers:formData.getHeaders()
  • 我在上面使用了
    async
    await
    ,如果您不喜欢,可以将它们更改为纯承诺语句
  • 为了添加自己的标题,只需
    headers:{…yourHeaders,…formData.getHeaders()}

以下新增内容:

var body = {
    userName: 'Fred',
    userEmail: 'Flintstone@gmail.com'
}

axios({
    method: 'post',
    url: '/addUser',
    data: body
})
.then(function (response) {
    console.log(response);
})
.catch(function (error) {
    console.log(error);
});
<input type="file" id="image" accept="image/png"/>
const formData = new FormData()

// add a non-binary file
formData.append('files[]', new Blob(['{"hello": "world"}'], { type: 'application/json' }), 'request.json')

// add a binary file
const element = document.getElementById('image')
const file = element.files[0]
formData.append('files[]', file, file.name)
await rc.post('/restapi/v1.0/account/~/extension/~/fax', formData)
浏览器 浏览器的
FormData
与NPM包“表单数据”不同。以下代码在浏览器中适用于我:

HTML:

var body = {
    userName: 'Fred',
    userEmail: 'Flintstone@gmail.com'
}

axios({
    method: 'post',
    url: '/addUser',
    data: body
})
.then(function (response) {
    console.log(response);
})
.catch(function (error) {
    console.log(error);
});
<input type="file" id="image" accept="image/png"/>
const formData = new FormData()

// add a non-binary file
formData.append('files[]', new Blob(['{"hello": "world"}'], { type: 'application/json' }), 'request.json')

// add a binary file
const element = document.getElementById('image')
const file = element.files[0]
formData.append('files[]', file, file.name)
await rc.post('/restapi/v1.0/account/~/extension/~/fax', formData)
退房

您可以按如下方式使用它:

var querystring = require('querystring');
axios.post('http://something.com/', querystring.stringify({ foo: 'bar' }));

上面的方法对我很有效,但因为这是我经常需要的,所以我对平面对象使用了一种基本方法。注意,我也在使用Vue,而不是REACT

packageData: (data) => {
  const form = new FormData()
  for ( const key in data ) {
    form.append(key, data[key]);
  }
  return form
}
这对我来说很有用,直到我遇到了更复杂的数据结构,其中包含嵌套的对象和文件,然后让我

packageData: (obj, form, namespace) => {
  for(const property in obj) {
    // if form is passed in through recursion assign otherwise create new
    const formData = form || new FormData()
    let formKey

    if(obj.hasOwnProperty(property)) {
      if(namespace) {
        formKey = namespace + '[' + property + ']';
      } else {
        formKey = property;
      }

      // if the property is an object, but not a File, use recursion.
      if(typeof obj[property] === 'object' && !(obj[property] instanceof File)) {
        packageData(obj[property], formData, property);
      } else {
        // if it's a string or a File
      formData.append(formKey, obj[property]);
      }
    }
  }
  return formData;
}

在我的例子中,我必须将边界添加到标题中,如下所示:

const form=new FormData();
append(item.name,fs.createReadStream(pathToFile));
常数响应=等待axios({
方法:“post”,
网址:'http://www.yourserver.com/upload',
数据:表格,
标题:{
“内容类型”:“多部分/表单数据;边界=${form.\u boundary}`,
},
});

如果您使用React Native,此解决方案也很有用。

更简单:

axios.post('/addUser',{
    userName: 'Fred',
    userEmail: 'Flintstone@gmail.com'
})
.then(function (response) {
    console.log(response);
})
.catch(function (error) {
    console.log(error);
});

在axios中使用application/x-www-form-urlencoded格式

默认情况下,axios将JavaScript对象序列化为JSON。发送数据 在application/x-www-form-urlencoded格式中,您可以使用 以下选项之一

浏览器

在浏览器中,可以使用URLSearchParams API,如下所示:

var querystring = require('querystring');
axios.post('http://something.com/', querystring.stringify({ foo: 'bar' }));
const params=新的URLSearchParams()

params.append('param1','value1')

params.append('param2','value2')

axios.post('/foo',参数)

请注意,并非所有浏览器都支持URLSearchParams(请参见caniuse.com),但有一个polyfill可用(请确保在全局环境中使用polyfill)

或者,您可以使用qs库对数据进行编码:

var body = {
    userName: 'Fred',
    userEmail: 'Flintstone@gmail.com'
}

axios({
    method: 'post',
    url: '/addUser',
    data: body
})
.then(function (response) {
    console.log(response);
})
.catch(function (error) {
    console.log(error);
});
<input type="file" id="image" accept="image/png"/>
const formData = new FormData()

// add a non-binary file
formData.append('files[]', new Blob(['{"hello": "world"}'], { type: 'application/json' }), 'request.json')

// add a binary file
const element = document.getElementById('image')
const file = element.files[0]
formData.append('files[]', file, file.name)
await rc.post('/restapi/v1.0/account/~/extension/~/fax', formData)
常数qs=要求('qs')

axios.post('/foo',qs.stringify({'bar':123}))

或以另一种方式(ES6),

从“qs”进口qs

常量数据={'bar':123}

常量选项={

方法:“POST”

标题:{'content type':'application/x-www-form-urlencoded'}

数据:qs.stringify(数据)

url,}

axios(可选)


2020 ES6工作方式

将html格式的表单绑定到数据中,如下所示:

数据:

提交人:

async submitForm() {
  const formData = new FormData()
  Object.keys(this.form).forEach((key) => {
    formData.append(key, this.form[key])
  })

  try {
    await this.$axios.post('/ajax/contact/contact-us', formData)
    this.$emit('formSent')
  } catch (err) {
    this.errors.push('form_error')
  }
}

在我的例子中,问题是FormData append操作的格式需要填写额外的“options”参数来定义文件名,因此:

var formData = new FormData();
formData.append(fieldName, fileBuffer, {filename: originalName});
我看到很多关于axios损坏的投诉,但实际上根本原因是没有正确使用表单数据。我的版本是:

"axios": "^0.21.1",
"form-data": "^3.0.0",
在接收端,我正在用multer处理这个问题,最初的问题是文件数组没有被填充-我总是在没有从流中解析文件的情况下返回请求

此外,有必要在axios请求中传递表单数据头集:

        const response = await axios.post(getBackendURL() + '/api/Documents/' + userId + '/createDocument', formData, {
        headers: formData.getHeaders()
    });
我的整个函数如下所示:

async function uploadDocumentTransaction(userId, fileBuffer, fieldName, originalName) {
    var formData = new FormData();
    formData.append(fieldName, fileBuffer, {filename: originalName});

    try {
        const response = await axios.post(
            getBackendURL() + '/api/Documents/' + userId + '/createDocument',
            formData,
            {
                headers: formData.getHeaders()
            }
        );

        return response;
    } catch (err) {
        // error handling
    }
}
“fieldName”的值并不重要,除非您有一些需要它的接收端处理。

它正在工作

//“内容类型”:“应用程序/x-www-form-urlencoded”, //犯下这个

import axios from 'axios';

let requestData = {
      username : "abc@gmail.cm",
      password: "123456
    };
   
    const url = "Your Url Paste Here";

    let options = {
      method: "POST",
      headers: { 
        'Content-type': 'application/json; charset=UTF-8',

        Authorization: 'Bearer ' + "your token Paste Here",
      },
      data: JSON.stringify(requestData),
      url
    };
    axios(options)
      .then(response => {
        console.log("K_____ res :- ", response);
        console.log("K_____ res status:- ", response.status);
      })
      .catch(error => {
        console.log("K_____ error :- ", error);
      });
获取请求

fetch(url, {
    method: 'POST',
    body: JSON.stringify(requestPayload),           
    headers: {
        'Content-type': 'application/json; charset=UTF-8',
        Authorization: 'Bearer ' + token,
    },
})
    // .then((response) => response.json()) .  // commit out this part if response body is empty
    .then((json) => {
        console.log("response :- ", json);
    }).catch((error)=>{
        console.log("Api call error ", error.message);
        alert(error.message);
});

我还需要计算内容长度

const formHeaders = form.getHeaders();
formHeaders["Content-Length"] = form.getLengthSync()

const config = {headers: formHeaders}

return axios.post(url, form, config)
.then(res => {
    console.log(`form uploaded`)
})

bodyFormData.set不是一个函数。我遇到了这个错误。您需要使用append而不是set。@ManojBhardwaj您需要绑定该函数,假设您在submit函数中发出请求,您需要绑定该函数。ex:-onSubmit={this.submit(bind(this)}或ex:-在构造函数(super){this.submit=this.submit.bind(this);}submit(){axios({});…}您的配置对象是错误的。它应该是:
{method:'post',url:'myurl',data:bodyFormData,headers:{'Content-Type':'multipart for