首页 > 解决方案 > 解析失败 SyntaxError:输入意外结束

问题描述

我正在尝试从 API 检索响应,但是在使用之后

fetch("url").then(res=>res.json()), 

在以下行中,我的代码中出现了意外的输入错误结束:

res => res.json(),

请找到下面的代码并帮助我准确定位我哪里出错了:-

static fetchCurrentServices(){      
   return   fetch("http://localhost:8080/portal-backend/services",   {
        mode: "no-cors",
        method: "GET" ,
        headers: {
          "Access-Control-Allow-Origin": "*",
          "Content-Type": "application/json"
        } 
  })
  .then(
    res => res.json() 
  ).catch(function (ex) {
   console.log('parsing failed', ex)
    });
  }

标签: reactjsapifetch

解决方案


您可以尝试下面的代码吗?我认为您错过了添加 {} 并添加了更多更改,请查看。

static fetchCurrentServices(){      
   return   fetch("http://localhost:8080/portal-backend/services",   {
        mode: "no-cors",
        method: "GET" ,
        headers: {
          "Access-Control-Allow-Origin": "*",
          "Content-Type": "application/json"
        } 
  }).then(res =>{
     return new Promise((resolve) => {
       if (res) {
        res.json().then(json => resolve(json)).catch(() => resolve(null))
      } else {
        resolve(null)
     }
   })

  }).catch(function (ex) {
   console.log('parsing failed', ex)
    });
  }

推荐阅读