提取将错误的数据从atat发送到后端

时间:2018-08-28 07:52:44

标签: javascript node.js reactjs api fetch

handleSubmit = e => {
e.preventDefault();
var data = new FormData();
data.append( "name", this.state.first_name + ' ' +this.state.last_name);
data.append( "password", this.state.password);
data.append( "email", this.state.email);
data.append( "phone_no", this.state.phone_no);
console.log(data)
fetch("http://localhost:8080/register",{
  method: "POST",
  body: data,
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded'
  }

})       .then(res => res.json())       。然后(         (结果)=> {             if(result.status =='失败'){                  警报(结果数据)                  console.log(结果)                 }其他{                     this.setState({                     isLoaded:是的,                   });                 }           // this.props.history.push('/ dashboard');         },         //注意:在这里处理错误很重要         //而不是catch()块,这样我们就不会吞咽         //组件中实际错误的异常。         (错误)=> {           this.setState({             isLoaded:是的,             错误           });         }       )   }

预期数据应该是

{ name: 'mayank', email: 'demo@gmail.com', password: 'password' }

返回的是

{ '------WebKitFormBoundarynYkonogmAGuTwWsy\r\nContent-Disposition: form-data; name': '"name"\r\n\r\   nMayank nauriyal\r\n------WebKitFormBoundarynYkonogmAGuTwWsy\r\nContent-Disposition: form-data; name   ="password"\r\n\r\npassword\r\n------WebKitFormBoundarynYkonogmAGuTwWsy\r\nContent-Disposition: form   -data; name="email"\r\n\r\nma@gmail.com\r\n------WebKitFormBoundarynYkonogmAGuTwWsy\r\nContent-Dispo   sition: form-data; name="phone_no"\r\n\r\n\r\n------WebKitFormBoundarynYkonogmAGuTwWsy--\r\n' }

1 个答案:

答案 0 :(得分:3)

发送JSON而不是FormData

var jsObject = {name: 'John', password: 'foo', email: 'foo@bar.com'};

fetch(url, {
  method: 'POST',
  body: JSON.stringify(jsObject),
  headers:{
    'Content-Type': 'application/json'
  }
}).then(res => res.json())
.then(response => console.log('Success:', response))
.catch(error => console.error('Error:', error));