1

I am trying to do a POST request through fetch in reactjs. I went through some docs but my error not solved.Can anyone please help me out?

Here is my reactjs code:

 handleSubmit(e) {
       e.preventDefault();
       var self = this;
    
       const payload = {
       id: 111,
       studentName: 'param',
       age: 24,
       emailId: 2
    };
    fetch({
       method: 'POST',
       url: 'http://localhost:8083/students',
       body: payload,
       headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json'
      }
     })
       .then(function(response) {
           return response.json()
         }).then(function(body) {
           console.log(body);
         });
     }
    
  }

If any one familiar with reactjs, just give a simple example how to call post request.Either by using fetch or axios.

Phil
  • 157,677
  • 23
  • 242
  • 245
Roy
  • 880
  • 7
  • 21
  • 39

2 Answers2

0

Here is an example..

  fetch('http://myAPiURL.io/login',{
    method:'POST',
    headers:{
        'Content-Type': 'application/json',
        'Accept': 'application/json'
    },
    body:JSON.stringify({
    email: userName,
    password: password
  })
  }).then(function (response) {

    //Check if response is 200(OK) 
    if(response.ok) {
      alert("welcome ");
    }
    //if not throw an error to be handled in catch block
    throw new Error(response);
  })
  .catch(function (error) {
    //Handle error
    console.log(error);
  });

for more info on how to use `fetch` https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
Sandeep
  • 585
  • 7
  • 19
0

Well I answered a similar question just now. here.

Well the great thing about React is that it's just Javascript.

So all you need is something to do a POST do your server!

You can use the native fetch function or a full-on library like axios

Examples using both could be:

// Using ES7 async/await
const post_data = { firstname: 'blabla', etc....};
const res = await fetch('localhost:3000/post_url', { method: 'POST', body: post_data });
const json = await res.json();

// Using normal promises
const post_data = { firstname: 'blabla', etc....};
fetch('localhost:3000/post_url', { method: 'POST', body: post_data })
.then(function (res) { return res.json(); })
.then(function (json) { console.log(json); };

// AXIOS example straight from their Github
axios.post('/user', {
    firstName: 'Fred',
    lastName: 'Flintstone'
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });
João Cunha
  • 9,929
  • 4
  • 40
  • 61