【问题标题】:Can't get response from ipify using fetch in React无法在 React 中使用 fetch 从 ipify 获得响应
【发布时间】:2020-10-15 19:03:22
【问题描述】:

在我的 React 应用程序中,我想在客户端获取用户的 IP 地址。我打算为此使用ipify。当我在浏览器中使用'http://api.ipify.org/?format=json' 时,它成功返回{"ip":"112.135.11.128"},但是当我通过fetch API 发出请求时,我无法得到相同的响应。我得到的是如下所示。

代码:

import React, { useEffect } from 'react';

const QRDisplay = () => {

    async function getIP(){
        const response = await fetch('https://api.ipify.org/?format=json');
        const data = await response.json();
        return response.status === 200 ? data : "err"
    }

    useEffect( () => {
        getIP().then(data => console.log(data))
    },[])

    return (
        <>
        </>  
    );
};

export default QRDisplay;

【问题讨论】:

    标签: reactjs fetch-api


    【解决方案1】:

    你需要调用 .json() 方法来获取body。

    async function getIP(){
        const response = await fetch('http://api.ipify.org/?format=json');
        const data = await response.json();
        return data;
    }
    

    那么你可以这样使用它:

    getIP().then(data => console.log(data);
    

    【讨论】:

    • 我也试过这个,但得到了Unhandled Rejection (SyntaxError): Unexpected end of JSON input
    • 不幸的是,它仍然抛出同样的错误。我不明白为什么
    • 我已经更新了答案。您可能需要在返回数据之前检查响应状态。如果您打算将其部署到 https 站点,请不要忘记将 url 中的 http 更改为 https
    • 我根据你的回答编辑了我的问题中的代码,但仍然得到同样的错误..
    【解决方案2】:

    Ozan Bulut 的类似方法

    await fetch('http://api.ipify.org/?format=json')
    .then(response => response.json())
    .then(data => {
     /* use data here */
    });
    

    【讨论】:

      猜你喜欢
      • 2019-10-03
      • 1970-01-01
      • 1970-01-01
      • 2022-01-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-25
      相关资源
      最近更新 更多