简体   繁体   English

通过axios的Reactjs POST请求

[英]Reactjs POST request through axios

Hi i am trying reactjs POST request through axios but getting error, I went through all docs but error is not solved. 嗨,我正在尝试通过axios的reactjs POST请求,但遇到错误,我遍历了所有文档,但错误未解决。

Here is my error: 这是我的错误:

Uncaught (in promise) Error: Request failed with status code 400 at createError (eval at (bundle.js:4621), :15:15) at settle (eval at (bundle.js:4615), :18:12) at XMLHttpRequest.handleLoad (eval at (bundle.js:4609), :77:7) 未捕获(按承诺)错误:请求在定居点(eval在(bundle.js:4615)::18:12)在createError(eval在(bundle.js:4621),: 15:15)处以状态代码400失败XMLHttpRequest.handleLoad(在(bundle.js:4609),:77:7处评估)

Here is my Reactjs code: 这是我的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>


   );
 }


}

Checking axios api the correct way of making POST request is: 检查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'
  }, 
})

There is no need of sending form data 无需发送表格数据

var data = new FormData();

Just pass json to via axios , 只需将json通过axios传递给,

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

Simple way to do : 简单的方法:

axios.post('http://localhost:8083/students',payload).then(...)
  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)
      })

Please follow the bellow steps to resolve 请按照以下步骤解决

First define the constructor 首先定义构造函数

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

write the handleSubmit Method 编写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);});
}

please don't forget bind the handleSubmit method 请不要忘记绑定handleSubmit方法

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

This will solved the problem 这样可以解决问题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM