如何正确做出反应中的api调用?

时间:2019-06-15 06:01:43

标签: node.js reactjs api

我想使用fetch从react js从虚拟API中获取结果。但是我从console.log()收到了“ SyntaxError:意外令牌

handleSubmit(event) {

fetch({
  url:'http://dummy.restapiexample.com/api/v1/employees',
  mode: 'cors',
  method: 'GET',
  dataType: 'json',
  headers: {
    'Access-Control-Allow-Origin':'*',
    'Content-Type': 'multipart/form-data'
  }
})
.then(response => response.json())
.then(data => {
    console.log(data);

})
.catch(error => {
    console.error(error);
});

event.preventDefault();
}

5 个答案:

答案 0 :(得分:0)

似乎您收到404响应,在转换为json时出现错误。 在下面的代码转换为json之前,我已经打印了响应。运行代码后检查控制台。

fetch({
  url:'http://dummy.restapiexample.com/api/v1/employees',
  mode: 'cors',
  method: 'GET',
  dataType: 'json',
  headers: {
    'Access-Control-Allow-Origin':'*',
    'Content-Type': 'multipart/form-data'
  }
})
.then(response => {
    console.log(response);
  response.json()})
.then(data => {
    console.log(data);

})
.catch(error => {
    console.error(error);
});

答案 1 :(得分:0)

后端出现问题时,通常会出现此错误。检查后端的API是否以json格式返回数据。

答案 2 :(得分:0)

Fetch的第一个参数是'url',第二个参数是'options'。尝试以下方法:

handleSubmit(event) {
    fetch('http://dummy.restapiexample.com/api/v1/employees', {
      mode: 'cors',
      method: 'GET',
      dataType: 'json',
      headers: {
        'Access-Control-Allow-Origin':'*',
        'Content-Type': 'multipart/form-data'
      }
    })
    .then(response => response.json())
    .then(data => {
        console.log(data);

    })
    .catch(error => {
        console.error(error);
    });
    event.preventDefault();
 }

答案 3 :(得分:0)

这是更新的

fetch('http://dummy.restapiexample.com/api/v1/employees')
  .then(function(response) {
    return response.json();
  })
  .then(function(data) {
    console.log("result",data);
  });

即使响应是 HTTP 404或500 ,从 fetch()返回的Promise也不会拒绝 HTTP错误状态。取而代之的是,它将正常解析(将ok状态设置为false),并且仅在网络出现故障或任何阻止请求完成的情况下才会拒绝。

我更希望将 Axios 与它一起使用,并适合于React应用程序。

axios.get( 'http://dummy.restapiexample.com/api/v1/employees')
            .then( response => {
              console.log("result",response.data)
            } )
            .catch( error => {
                 console.log("error",error)
            } );

答案 4 :(得分:0)

这种情况发生在您向服务器发出请求并将响应解析为JSON,但不是JSON时。

fetch('http://dummy.restapiexample.com/api/v1/employees').then(res => res.json())

实际请求工作正常。得到了回应。但是res.json()失败了。

Read this for more suggestion

相关问题