生成随机回调函数名,避免回调函数名相同造成获取返回数据混乱

const makeCallbackName = () => {
  const timestamp = Date.now();
  const randomNum = Math.round(Math.random() * 1000);
  return `callback_${timestamp}_${randomNum}`;
}

jsonp解决跨域

export const jsonpReq = () => {
  // 接口请求地址
  const reqInterface = 'xxxxx'
  const callbackName = makeCallbackName();

  try {
    return new Promise((resolve, reject) => {
       // 后端调用callback返回数据
      window[callbackName] = (result: any) => {
        resolve(result);
      }
      const JSONP = document.createElement('script');
      JSONP.type = 'text/javascript';
      JSONP.src = `${reqInterface}?callback=${callbackName}`;
      document.body.appendChild(JSONP);
      setTimeout(() => {
        document.body.removeChild(JSONP)
      }, 100)
    })
  } catch (error) {
    console.log('JSONP error-----', error);
  }
};

使用

const getJsonpData = async () => {
   const res = await jsonpReq();
   console.log('res----', res)
}

深邃烟海
0 声望0 粉丝

« 上一篇
git 撤销merge