【问题标题】:How to consume an fetch api with reactjs? [duplicate]如何使用 reactjs 使用 fetch api? [复制]
【发布时间】:2019-02-12 01:34:23
【问题描述】:

我有一个用 PHP 制作的 API,但我想通过 fetch 使用 Reactjs,但我无法获得,有人可以帮助我吗?

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

错误:

这里的邮递员:

【问题讨论】:

标签: javascript reactjs rest cors fetch


【解决方案1】:

试试

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

   })
 }

【讨论】:

  • 在 console.log 中返回:SyntaxError: JSON.parse: unexpected end of data at line 1 column 1 of the JSON data[了解更多]
  • 两个反对票一个赞成票,答案被接受...我不确定是否应该删除该帖子。谁能告诉我有什么不满意的地方,我可以编辑一下
猜你喜欢
  • 2023-01-23
  • 1970-01-01
  • 2021-12-18
  • 2018-09-19
  • 2020-08-12
  • 2019-11-16
  • 2017-03-08
  • 2019-11-25
  • 2017-04-08
相关资源
最近更新 更多