Ad

How To Consume An Fetch Api With Reactjs?

- 1 answer

I have one API made in PHP, but i want consume with Reactjs using fetch, but i can not get, someone can help me?

handleSubmit = event => {

  event.preventDefault();
  const email = document.querySelector(".email").value;
  const senha = document.querySelector(".password").value;

  alert(JSON.stringify({email, senha}));

  const res = {
     method: 'POST',
     mode:'no-cors',
     body: JSON.stringify({email,senha}),
     headers: new Headers({
       'Content-type': 'application/json',
       'Authorization': 'token here',
     }),
   };
   fetch('http://rhvagas-api/login', res).then(res => {})
   .then(result => {
      console.log(res);
      return result.json();
   })
 }

Error: enter image description here

POSTMAN HERE: enter image description here

Ad

Answer

Try

handleSubmit = event => {

  event.preventDefault();
  const email = document.querySelector(".email").value;
  const senha = document.querySelector(".password").value;

  alert(JSON.stringify({email, senha}));

  const res = {
     method: 'POST',
     mode:'no-cors',
     body: JSON.stringify({email,senha}),
     headers: new Headers({
       'Content-type': 'application/json',
       'Authorization': 'token here',
     }),
   };
   fetch('http://rhvagas-api/login', res).then(res => res.json())
   .then(result => {
      console.log(result);
      // work with the result

   })
 }
Ad
source: stackoverflow.com
Ad