javascript fetch() 中断执行并抛出 404

问题描述 投票:0回答:1

我有一个静态的 azure Web 应用程序和一个 azure 函数,两者都在本地运行。该功能正在运行并在浏览器中显示结果。

该应用程序是一个普通的 JavaScript 应用程序。我有以下代码:

获取功能

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);
    });
   
}

当我访问网络应用程序网址:http://127.0.0.1:5500/Bogot%C3%A1时,它成功路由,然后进入获取功能并崩溃,行中没有任何消息“ const 响应 = 等待 fetch("http://localhost:7071/api/GetResources/Bogotá");"。或者如果我不进入该方法,它会到达加载内容函数中的“resources.forEach((resource)”。一旦我再次按F10,它就会崩溃。

结果是:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Error</title>
</head>
<body>
    <pre>Cannot GET /Bogot%C3%A1</pre>
</body>
</html>

消息是:

波哥特%C3%A1:1

    GET http://127.0.0.1:5500/Bogot%C3%A1 404 (Not Found)

该响应来自网络应用程序而不是函数。在函数输出中我得到了这个。

[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)

我不知道我错过了什么。我了解该函数已正确运行并已发送响应,但网络应用程序未收到它。

javascript azure-functions single-page-application azure-static-web-app
1个回答
0
投票

我尝试了你的代码,并遇到了 url 中带有

Bogot%C3%A1
Bogotá
错误。 error of Bogot%C3%A1 更新您的前端代码 URL,如下所示:

     const url = `http://localhost:7071/api/HttpTrigger1?city=${encodeURIComponent(city)}`;

我使用了示例 azure 函数代码,并在

?city=Bogotá
下加载了示例数据:

module.exports = async function (context, req) {
    context.log('JavaScript HTTP trigger function processed a request.');
    const city = req.query.city || (req.body && req.body.city);

    if (!city) {
        context.res = {
            status: 400,
            body: "Please pass a city in the query string or in the request body."
        };
        return;
    }

    const resources = {
        "Bogotá": [
            { name: "Resource 1", coordinator: "John Doe", time: "10:00 AM", whatsappGroup: "#" },
            { name: "Resource 2", coordinator: "Jane Doe", time: "02:00 PM", whatsappGroup: "#" }
        ],
        "Medellín": [
            { name: "Resource A", coordinator: "Carlos Pérez", time: "11:00 AM", whatsappGroup: "#" },
            { name: "Resource B", coordinator: "Ana Gómez", time: "03:00 PM", whatsappGroup: "#" }
        ]
    };

    const cityResources = resources[city];

    if (!cityResources) {
        context.res = {
            status: 404,
            body: `No resources found for city: ${city}`
        };
    } else {
        context.res = {
            status: 200,
            body: cityResources
        };
    }
};



Out pout witrh ?city=Bogotá

确保在

local.settings.json
中添加CORS:

 "Host": {
"CORS": "*"
}

下面是显示

?city=Bogotá

数据的示例前端代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>City Resources</title>
    <style>
        body {
            font-family: Arial, sans-serif;
        }
        .resource-list {
            margin-top: 20px;
        }
        .resource-item {
            margin-bottom: 15px;
        }
    </style>
</head>
<body>
    <h1>City Resources</h1>
    
    <input type="text" id="city" placeholder="Enter city name" />
    <button onclick="getCityResources()">Get Resources</button>

    <div id="resources-container" class="resource-list"></div>

    <script>
 
        async function getCityResources() {
            const city = document.getElementById('city').value.trim();
            if (!city) {
                alert('Please enter a city name.');
                return;
            }

            const url = `http://localhost:7071/api/HttpTrigger1?city=${encodeURIComponent(city)}`;

            try {
                const response = await fetch(url);
                const data = await response.json();
                const container = document.getElementById('resources-container');
                container.innerHTML = ''; 

                if (Array.isArray(data) && data.length > 0) {
                   
                    data.forEach(resource => {
                        const resourceElement = document.createElement('div');
                        resourceElement.classList.add('resource-item');
                        resourceElement.innerHTML = `
                            <h3>${resource.name}</h3>
                            <p>Coordinator: ${resource.coordinator}</p>
                            <p>Time: ${resource.time}</p>
                            <p>Whatsapp: <a href="${resource.whatsappGroup}" target="_blank">Join Group</a></p>
                        `;
                        container.appendChild(resourceElement);
                    });
                } else {
                    container.innerHTML = `<p>No resources found for ${city}.</p>`;
                }
            } catch (error) {
                console.error('Error fetching data:', error);
                alert('An error occurred while fetching resources.');
            }
        }
    </script>
</body>
</html>

我参考了此链接,使用 Azure Functions 将 API 添加到 Azure 静态 Web 应用。

要初始化 Azure 静态 Web 应用项目,请安装静态 Web 应用 CLI 并使用

swa init -y
命令。

swa-cli.config.json:

{
  "$schema": "https://aka.ms/azure/static-web-apps-cli/schema",
  "configurations": {
    "new-folder": {
      "appLocation": "scr",
      "apiLocation": ".",
      "outputLocation": ".",
      "apiLanguage": "node",
      "apiVersion": "16",
      "apiBuildCommand": "npm run build --if-present"
    }
  }
}


使用

swa start
启动 Azure 静态 Web 应用 (SWA) 项目的本地开发服务器

saw srat ouput

Outpu to feach

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.