请求一个JS文件并返回

更新时间: 2024-04-07 10:34:06

本文介绍请求一个JS文件并返回示例场景及结果。

代码

/**
 * 示例为请求https://demo.aliyundoc.com/alipay/qrcode/1.0.3/qrcode.js并返给客户端
 * 测试时请将someHost和url替换为您自己的地址
 */
const someHost = "https://demo.aliyundoc.com/alipay/qrcode/1.0.3/";
const url = someHost + "qrcode.js";
/**
 * gatherResponse等待获取response body完成并处理成string返给客户端
 * 使用await gatherResponse(..) 在1个异步函数确保完整获取response body
 */
async function gatherResponse(response) {
  const headers = response.headers;
  const contentType = headers.get("content-type") || "";
  if (contentType.includes("application/json")) {
    return JSON.stringify(await response.json());
  } else if (contentType.includes("application/text")) {
    return response.text();
  } else if (contentType.includes("text/html;charset=UTF-8")) {
    return response.text();
  } else {
    return response.blob();
  }
}

async function handleRequest() {
  const init = {
    headers: {
      "content-type": "application/json;charset=UTF-8",
    },
  };
  const response = await fetch(url, init);
  const results = await gatherResponse(response);
  return new Response(results, init);
}

addEventListener("fetch", event => {
  return event.respondWith(handleRequest());
});

结果

ER内请求 https://demo.aliyundoc.com/alipay/qrcode/1.0.3/qrcode.js 并返回给客户端。

请求