自学内容网 自学内容网

vue3 通过 axios + jsonp 实现根据公网 ip, 查询天气信息

前提

安装 axios 的 jsonp 适配器。

pnpm install @pingtou/axios-jsonp

简单使用说明:当与后端约定的请求 callback 参数名称不为为 callback 时,可修改。一般无需添加。
在这里插入图片描述

1. 获取当前电脑 ip 和城市信息

请求地址: https://whois.pconline.com.cn/ipJson.jsp?ip=&jsonp=true
注意添加 jsonp = true。 使用 jsonp 的方式,避免生产环境出现跨域无法访问。

import axios from 'axios';
import { jsonpAdapter } from '@pingtou/axios-jsonp';

// 获取当前设备访问的 ip 地址,返回 ip 和城市信息
export async function fetchGetIpAndCity() {
  try {
    // 线上会出现跨域,使用 jsonp 请求
    return axios({
      url: 'https://whois.pconline.com.cn/ipJson.jsp?ip=&jsonp=true',
      adapter: jsonpAdapter,
    });
  } catch (error) {
    return '';
  }
}

返回如下:
在这里插入图片描述

2.根据上一步返回的城市信息,调用腾讯天气接口

请求地址:https://wis.qq.com/weather/common?source=pc&weather_type=observe&province=${province}&city=${city}&jsonp=true

传入省市,注意添加 jsonp=true

// 获取天气

export async function fetchGetWeather(province: string, city: string) {
  try {
    // 通过 jsonp 请求,避免线上请求时跨域
    return axios({
      url: `https://wis.qq.com/weather/common?source=pc&weather_type=observe&province=${province}&city=${city}&jsonp=true`,
      adapter: jsonpAdapter,
    });
  } catch (error) {
    return {};
  }
}

效果:
在这里插入图片描述


原文地址:https://blog.csdn.net/weixin_39786582/article/details/142496071

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!