2022.10.17 - 经验:获取当前归属地
2022.10.17 - 经验:获取当前归属地
参考原文: IP属地获取,前端获取用户位置信息
尝试使用 pv.sohu.com/cityjson?ie… 获取用户位置信息, 成功获取到信息,信息样本如下:
{"cip": "14.11.11.11", "cid": "440000", "cname": "广东省"}
请求方法:
methods: {
async getIpAndAddressSohu() {
const config = {
headers: {
Accept: 'application/json',
'Content-Type': 'application/json;charset=UTF-8'
}
};
const currentAxios = axios.create();
let res = await currentAxios.get('/apiSohu/cityjson?ie=utf-8', config)
const info = res.data.substring(19, res.data.length - 1);
return JSON.parse(info).cname;
},
async ipArea() {
this.address = await this.getIpAndAddressSohu() || '监利市';
},
}
// 需要做跨域处理
getIpAndAddressSohu(){
// config 是配置对象,可按需设置,例如 responseType,headers 中设置 token 等
const config = {
headers: {
Accept: 'application/json',
'Content-Type': 'application/json;charset=UTF-8',
},
}
axios.get('/apiSohu/cityjson?ie=utf-8', config).then(res => {
console.log(res.data) // var returnCitySN = {"cip": "14.11.11.11", "cid": "440000", "cname": "广东省"};
const info = res.data.substring(19, res.data.length - 1)
console.log(info) // {"cip": "14.11.11.11", "cid": "440000", "cname": "广东省"}
this.ip = JSON.parse(info).cip
this.address = JSON.parse(info).cname
})
}
调试的时候,做了跨域处理。
proxy: {
'/apiSohu': {
target: 'http://pv.sohu.com/', // localhost=>target
changeOrigin: true,
pathRewrite: {
'/apiSohu': '/'
}
},
}
下面是一张获取到位置信息的效果图:


浙公网安备 33010602011771号