Reactjs POST请求通过axios

新手上路,请多包涵

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

这是我的错误:

未捕获(承诺)错误:请求失败,状态码为 400 XMLHttpRequest.handleLoad(在(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>

   );
 }

}

原文由 Roy 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 310
2 个回答

检查 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'
  },
})

原文由 mersocarlin 发布,翻译遵循 CC BY-SA 3.0 许可协议

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

原文由 SM Chinna 发布,翻译遵循 CC BY-SA 3.0 许可协议

推荐问题