【问题标题】:Reading GET in REACT serves NODEJS在 REACT 中读取 GET 服务于 NODEJS
【发布时间】:2020-11-01 21:27:35
【问题描述】:

我用 REACT 语言编写了一个从服务器 (NODEJS) 接收我的列表的函数

        getList = () => {
       const request = new Request('http://localhost:3000/api/get');
  
       fetch(request, {method: 'GET',mode: 'no-cors',
        })
       .then((response) => console.log("response", response.JSON()));
        }

正在发出请求,但我在 CONSOLE.LOG 中收到的返回值为:

          response Response {type: "opaque", url: "", redirected: false, status: 0, ok: 
          false, …}body: (...)bodyUsed: falseheaders: Headers {}ok: falseredirected: falsestatus: 
          0statusText: ""type: "opaque"url: ""__proto__: Response

这是服务器上的代码:

             const MyList=[
             {id:1,name:'to do list'},
             {id:2,name:'to sleep'},
             ]
             app.get('/api/get',(req,res)=>{
             res.send(MyList);
             });

服务器返回的列表的值在哪里???

【问题讨论】:

标签: node.js reactjs api


【解决方案1】:

可以从 response.body 访问来自服务器的数据,但是 response.json() 返回一个承诺,因此您必须执行以下操作:

getList = () => {
    const request = new Request('http://localhost:3000/api/get');

    fetch(request, {method: 'GET',mode: 'no-cors'})
    .then((response) => response.json().then(json => {
          console.log(json.body);
    });
}

【讨论】:

  • @semicolon 您是否尝试过将您的 API 与您的 react 应用程序分开测试? IE。通过使用邮递员
【解决方案2】:

我在响应中添加了 .json:

      getList = () => {
      const request = new Request('http://localhost:3000/api/get');
  
      fetch(request, {method: 'GET',mode: 'no-cors' })
      .then((response) => console.log("response", response.json()));
      }

并收到以下错误:

     TobuyList.js:30 Uncaught (in promise) SyntaxError: Unexpected end of input
     at TobuyList.js:30

【讨论】:

    【解决方案3】:

    在您的服务器中,将 res.send 更改为 res.json

    在客户端(取自mozilla docs):

    fetch('http://localhost:3000/api/get', { mode: 'no-cors' })
      .then(response => response.json())
      .then(data => console.log(data));
    

    【讨论】:

    • 我仍然得到同样的错误:TobuyList.js:31 Uncaught (in promise) SyntaxError: Unexpected end of input at TobuyList.js:31
    • 这可能是 CORS 的问题,stackoverflow.com/questions/45696999/…,如果不需要 CORS,请尝试删除该选项,看看是否有效。
    猜你喜欢
    • 1970-01-01
    • 2021-04-12
    • 1970-01-01
    • 2018-07-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-07
    • 1970-01-01
    相关资源
    最近更新 更多