感谢您访问我的问题。最近,我正在研究搜索引擎产品,需要了解客户的国家/地区代码。我尝试使用下面的URL来获取它,并返回服务器端国家代码。
https://extreme-ip-lookup.com/json/
请让我知道在getInitialProps时如何获取正确的用户国家/地区代码。
您可以这样操作:
import React from 'react';
import fetch from 'isomorphic-unfetch';
// ZEIT has created a data-fetching library called SWR (client side).
import useSWR from 'swr';
const API_URL = 'https://extreme-ip-lookup.com/json/';
async function fetcher(url) {
const res = await fetch(url);
const json = await res.json();
return json;
}
function Index() {
const { data, error } = useSWR(API_URL, fetcher);
if (error) return <div>failed to load</div>;
if (!data) return <div>loading...</div>;
const { countryCode } = data;
return (
<div>
<p>Country Code: {countryCode}</p>
</div>
);
}
export default Index;