JSONP解决跨域问题

在写前端界面定位的时候,之前使用的是封装的接口,然后前端去请求,获得地点,但是那样子请求ip是服务器的ip,导致定位也是那边,本地fetch请求又产生跨域问题。

city-locator:1 Access to fetch at 'https://h5gw.map.qq.com/ws/location/v1/ip?callback=window._JSONP_callback.JSONP6476&ip=&key=xxx&apptag=h5loc_ip_loc&output=jsonp&t=' from origin 'http://localhost:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

注意看这里,output=jsonp,可以发现请求是支持输出为JSONP格式的,这个时候就可以通过引入JSONP来解决。JSONP 是一种古老的跨域解决方案,它利用

      // 封装 JSONP 请求函数
      function jsonp(url, callback) {
        const callbackName = `jsonp_callback_${Math.round(100000 * Math.random())}`;
        window[callbackName] = function (data) {
          delete window[callbackName];
          const script = document.querySelector(`script[src^="${url}&callback=${callbackName}"]`);
          if (script) {
            script.parentNode.removeChild(script);
          }
          callback(data);
        };

        const script = document.createElement('script');
        script.src = `${url}&callback=${callbackName}`;
        document.body.appendChild(script);
      }
            const getCurrentCity = () => {
        const ipLocationUrl = 'https://h5gw.map.qq.com/ws/location/v1/ip?ip=&key=xxxx&apptag=h5loc_ip_loc&output=jsonp';
        jsonp(ipLocationUrl, (data) => {
          try {
            if (data.status === 0) {
              let city = data.result['ad_info'].city;
              la.value = data.result['location']['lat'];
              ln.value = data.result['location']['lng'];
              cityDetail.value = cities.value.find(c => c.label === city);

              if (cityDetail.value) {
                currentCity.value = cityDetail.value.label;
                tishi.value = '返回门店';
                canGoBack.value = true;
              } else {
                tishi.value = '定位失败,请手动选择城市';
              }
            } else {
              throw new Error('IP 定位请求失败');
            }
          } catch (error) {
            tishi.value = '定位失败,请手动选择城市';
            console.error('定位失败,请手动选择城市:', error);
          }
        });
      };

再次运行界面,可以看到返回值是这样子的:

jsonp_callback_89153 && jsonp_callback_89153({
    "status": 0,
    "message": "Success",
    "request_id": "7fa8183b4d9943c3b7956761fac13036",
    "result": {
        "ip": "220.xxx.xxx.230",
        "location": {
            "lat": 37.73605,
            "lng": 112.56566
        },
        "ad_info": {
            "nation": "中国",
            "province": "山西省",
            "city": "太原市",
            "district": "小店区",
            "adcode": 140105,
            "nation_code": 156
        }
    }
});