【问题标题】:fetch API always returns {"_U": 0, "_V": 0, "_W": null, "_X": null}fetch API 总是返回 {"_U": 0, "_V": 0, "_W": null, "_X": null}
【发布时间】:2021-03-02 12:10:27
【问题描述】:

下面的代码总是返回下面的连线对象

{“_U”:0,“_V”:0,“_W”:空,“_X”:空}

作为回应。

这是我的代码

    getData = () => {
        fetch('http://192.168.64.1:3000/getAll',{
            method: 'GET',
            headers: {
                Accept: 'application/json',
                'Content-Type': 'application/json'
            }
        })
        .then((response) => {
            console.log('Response:')
            console.log(response.json())
            console.info('=================================')
        })
        .catch(err => console.error(err));

    } 

    componentDidMount(){
        this.getData();
    }

我使用 node、express、Mysql 作为后端和 react-native 前端

我的后端代码在这里

app.get('/getAll',(req,res) => {
    console.log('getAll method Called');
    con.query('select * from dummy',(err,results,fields) => {
        if(err) throw err;
        console.log('Response');
        console.log(results);
        res.send(results);
    });
});

上面的代码在控制台中给出了正确的输出,但 fetch API 不是。

我找不到我的问题的解决方案。提前致谢。

【问题讨论】:

  • 你用什么做后端服务器?
  • 我正在使用 node 和 express
  • 您是否查看过浏览器调试工具的网络选项卡以查看原始有效负载的样子?
  • 我正在研究 react-native 兄弟
  • response.json() 返回一个承诺。

标签: mysql node.js reactjs react-native fetch


【解决方案1】:

这表明您在承诺解决之前正在记录承诺 - 当您执行以下操作时的结果: console.log(response.json())

How do I access promise callback value outside of the function?

正如@Evert 在 cmets 中正确指出的那样,这是因为 response.json() 返回一个 promise 对象。

因此,在您调用 response.json() 后,您需要链接一个额外的 .then(),并在其中记录已解决的承诺。

getData = () => {
    fetch('http://192.168.64.1:3000/getAll',{
        method: 'GET',
        headers: {
            Accept: 'application/json',
            'Content-Type': 'application/json'
        }
    })
    .then(response => response.json())
    .then(data => {
        console.log(data);
    })
    .catch(err => console.error(err));
} 

【讨论】:

    【解决方案2】:

    asyncawait 添加到您的代码中:

    getData = async () => {
       await fetch('http://192.168.64.1:3000/getAll',{
            method: 'GET',
            headers: {
                Accept: 'application/json',
                'Content-Type': 'application/json'
            }
        })
        .then((response) => {
            console.log('Response:')
            console.log(response.json())
            console.info('=================================')
        })
        .catch(err => console.error(err));
    
    } 
    

    【讨论】:

      【解决方案3】:

      所以问题是你没有等待你的 Promise 解决,这很容易解决。

      try {
        const res = await fetch(
          'your_api',
        );
        const data = await res.json();
      } catch (error) {
          console.log(error);
      } 
      

      【讨论】:

        猜你喜欢
        • 2022-01-14
        • 2021-04-21
        • 2022-01-14
        • 1970-01-01
        • 2022-01-05
        • 2021-11-26
        • 1970-01-01
        • 2021-12-20
        相关资源
        最近更新 更多