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': '/'
    }
  },
}

下面是一张获取到位置信息的效果图:

image-20221017112804299

posted @   吕业浩  阅读(40)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
点击右上角即可分享
微信分享提示