【问题标题】:Reactjs POST request through axiosReactjs 通过 axios 发出 POST 请求
【发布时间】:2018-04-25 21:25:09
【问题描述】:

您好,我正在通过 axios 尝试 reactjs POST 请求,但出现错误,我浏览了所有文档,但错误未解决。

这是我的错误:

未捕获(承诺中)错误:请求失败,状态码为 400 在 createError (eval at (bundle.js:4621), :15:15) 结算时(eval at (bundle.js:4615), :18:12) 在 XMLHttpRequest.handleLoad (eval at (bundle.js:4609), :77:7)

这是我的 Reactjs 代码:

import React from 'react';
import RaisedButton from 'material-ui/RaisedButton';
import TextField from 'material-ui/TextField';
import axios from 'axios';
const style = {
 margin: 15,
marginLeft: 600
};
export default class  Register extends React.Component {
 constructor(props) {
   super(props);
   this.onSubmit=this.handleSubmit.bind(this);
}


handleSubmit(e) {
   e.preventDefault();
   var self = this;
   var data = new FormData();
   const payload = {
   id: 111,
   studentName: 'param',
   age: 24,
   emailId: 2
};
data.append("myjsonkey", JSON.stringify(payload));

axios('http://localhost:8083/students',{
   method: 'POST',
   body: data,
   headers: {
    // 'Authorization': `bearer ${token}`,
    'Content-Type': 'application/json'
  }
 })
   .then(function(response) {
       return response.json()
     }).then(function(body) {
       console.log(body);
     });
 }

render() {
   return (
     <form onSubmit={this.onSubmit}>
     <div style={style}>
     <TextField ref='id'
     hintText="Enter Student id"
     floatingLabelText="id"
     />
     <br/>
     <TextField ref='sname'
     hintText="Enter your Last Name"
     floatingLabelText="StudentName"
     />
     <br/>
     <TextField ref='age'
     hintText="Enter your Age"
     floatingLabelText="age"
     />
     <br/>

     <TextField ref='emailId'
     hintText="Enter your Email"
     floatingLabelText="emailId"
     />
     <br/>
     <br/>
     <input type="submit" />


     </div>
         </form>


   );
 }


}

【问题讨论】:

标签: javascript java reactjs axios


【解决方案1】:

请按照以下步骤解决

首先定义构造函数

 constructor(props) {
        super(props);
        this.state = {
                id: ,
       studentName: '',
               age: ,
           emailId: '',
        };

编写handleSubmit方法

handleSubmit (evt) {
    evt.preventDefault();
    console.log("Submit");
    const payload = {
                 id : this.state.id,
        studentName : this.state.studentName,
                age : this.state.age,
            emailId : this.state.emailId,  
    }

    axios({
        method: 'post',
        url: 'url-url',
        data: payload, 

    }).then(function(response) {
        console.log(response);
    }).catch(function (error){
        console.log(error);});
}

请不要忘记绑定 handleSubmit 方法

this.handleSubmit = this.handleSubmit.bind(this);

这样就解决了问题

【讨论】:

    【解决方案2】:
      var authOptions = {
         method: 'post',
         url: 'https://exam.com/apps',
         data: JSON.stringify({"name": "ddd"});,
         headers: {
           'Content-Type': 'application/json'
          },
         json: true
        };
     axios(authOptions)
        .then((response) => {
            console.log(response);
            })
        .catch((error) => {
           alert(error)
          })
    

    【讨论】:

      【解决方案3】:

      检查axios api发出POST请求的正确方法是:

      const payload = {
        id: 111,
        studentName: 'param',
        age: 24,
        emailId: 2
      }
      
      axios({
        method: 'post',
        url: '/user/12345',
        data: payload, // you are sending body instead
        headers: {
         // 'Authorization': `bearer ${token}`,
        'Content-Type': 'application/json'
        }, 
      })
      

      【讨论】:

      • @SpRaju 删除 FormDataJSON.stringify 实现。您可以将数据作为 JavaScript 对象发布。我也更新了我的答案:)
      【解决方案4】:

      无需发送表单数据

      var data = new FormData();
      

      只需将 json 传递给 via axios ,

      axios('http://localhost:8083/students',{
         method: 'POST',
         data : payload,
         headers: {
          // 'Authorization': `bearer ${token}`,
          'Content-Type': 'application/json'
        }
      })
      

      简单的做法:

      axios.post('http://localhost:8083/students',payload).then(...)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-12-04
        • 2018-10-31
        • 2018-04-25
        • 2020-09-21
        • 2018-09-13
        • 1970-01-01
        • 2021-06-07
        • 2021-05-07
        相关资源
        最近更新 更多