You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

本地Azure静态Web应用调用Azure Function时fetch触发404问题排查

本地Azure静态Web应用调用Azure Function时崩溃并返回404问题

问题背景

本地同时运行原生JavaScript的Azure静态Web应用和Azure Function,Function单独在浏览器中请求可正常返回结果,但Web应用调用时出现崩溃:访问http://127.0.0.1:5500/Bogot%C3%A1时路由能匹配,但执行fetch后崩溃,页面返回来自Web应用的404,而Azure Function日志显示已成功执行并返回结果。

相关代码

fetch函数

async function fetchResources(city) {
    try {
      const response = await fetch("http://localhost:7071/api/GetResources/Bogotá");
      
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }
      
      const data = await response.json();
      console.log(data);
      
      return data;
    } catch (error) {
      console.error('Error fetching data:', error);
      //cityListContainer.innerHTML = `<p>Lo sentimos, no pudimos cargar los datos.</p>`;
    }
}

路由匹配与内容加载代码

else if (path === "/Bogotá") {
    const resources = fetchResources("Bogotá");
     
    resources.forEach((resource) => {
        const item = document.createElement('div');
        item.innerHTML = `
        <h3>${resource.name}</h3>
        <p>Coordinador: ${resource.coordinator}</p>
        <p>Hora: ${resource.time}</p>
        <a href="${resource.whatsappGroup}" target="_blank">Grupo de WhatsApp</a>
        `;
        container.appendChild(item);
    });
   
}

错误现象

  1. 页面返回404响应(来自Web应用):
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Error</title>
</head>
<body>
    <pre>Cannot GET /Bogot%C3%A1</pre>
</body>
</html>
  1. 控制台报错:
Bogot%C3%A1:1
    GET http://127.0.0.1:5500/Bogot%C3%A1 404 (Not Found)
  1. Azure Function执行日志(显示成功):
[2024-11-22T22:19:59.560Z] Executing 'Functions.GetResources' (Reason='This function was programmatically called via the host APIs.', Id=fe5e3e91-c355-4fa5-9253-09b3206f954d)
[2024-11-22T22:19:59.572Z] C# HTTP trigger function processed a request.
[2024-11-22T22:19:59.573Z] Executing OkObjectResult, writing value of type 'Azure.Core.PageableHelpers+FuncPageable`1[[Azure.Data.Tables.TableEntity, Azure.Data.Tables, Version=12.9.1.0, Culture=neutral, PublicKeyToken=92742159e12e44c8]]'.
[2024-11-22T22:20:00.175Z] Executed 'Functions.GetResources' (Succeeded, Id=fe5e3e91-c355-4fa5-9253-09b3206f954d, Duration=615ms)

问题根源与修复方案

1. 异步函数未正确等待导致崩溃

fetchResources是异步函数,直接赋值给resources得到的是Promise对象,而非实际数据。调用resources.forEach会直接报错,因为Promise没有forEach方法,这个错误会引发页面路由逻辑异常,最终触发Web应用的404 fallback。

修复代码:
将外层路由处理函数声明为异步,并添加await等待数据返回,同时增加空值判断:

// 外层路由处理函数需声明为async
else if (path === "/Bogotá") {
    // 等待异步函数返回实际数据
    const resources = await fetchResources("Bogotá");
    // 避免catch分支返回undefined导致后续报错
    if (resources) {
        resources.forEach((resource) => {
            const item = document.createElement('div');
            item.innerHTML = `
            <h3>${resource.name}</h3>
            <p>Coordinador: ${resource.coordinator}</p>
            <p>Hora: ${resource.time}</p>
            <a href="${resource.whatsappGroup}" target="_blank">Grupo de WhatsApp</a>
            `;
            container.appendChild(item);
        });
    }
}

2. 路径编码不匹配优化

访问URL是编码后的/Bogot%C3%A1,但路由判断用的是未解码的/Bogotá,部分静态服务器可能不会自动解码路径,导致路由匹配异常。可统一处理路径编码:

// 解码当前路径后再做匹配
const decodedPath = decodeURI(window.location.pathname);
if (decodedPath === "/Bogotá") {
    // 后续逻辑同上
}

3. CORS配置验证

确认Azure Function本地配置是否允许Web应用的来源,检查local.settings.json中的CORS字段:

{
  "Values": {
    // 其他配置项
  },
  "Host": {
    "CORS": "http://127.0.0.1:5500"
  }
}

内容的提问来源于stack exchange,提问作者Ricker Silva

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.16 01:57:18