对 Azure 函数的 Ajax 调用不返回任何数据

问题描述

这是我第一次使用 Azure Functions。我正在尝试使用在标头中传递的身份验证令牌访问第 3 方 API。当我在本地单独运行 Azure 函数时,我已经成功取回数据,因为它将正确的数据记录到我的控制台。我已经将这个基本功能部署到 Azure,并将 * 添加到 CORS 列表中进行测试。但是,当我创建一个简单的 HTML 文件以在我们的网站上使用脚本标记中的 ajax 托管以获取此数据时 - 以便我最终可以在 html 页面显示它 - 没有返回任何内容。我还没有找到任何其他使用我的特定代码库或使用如此简单代码的示例。没有错误消息,它只是记录''。这是我的 html/JS 脚本:

<script type="text/javascript">
$(document).ready(function () {
    console.log("fired off on ready...");
    var url = "https://{...}.azurewebsites.net/api/{...}?"
    
       $.ajax({
           method: "GET",url: url,crossDomain: true,success: function (respData) {
               console.log(respData);
                $("#functionData").html("<div style='padding: 5em 1em; text-align: center; color: #008800'>" + respData + "</div>");
           },error: function (jqXHR) {
              console.log(jqXHR)
              $("#functionData").html("<div style='padding: 1em; text-align: center; color: #660000'>Sorry,an error occurred: " + jqXHR.responseText + "</div>");
          }
       });
    })
</script>

这是我的 Azure 函数中的 index.js 文件


module.exports = async function(context) {

var config = {
  method: 'get',url: 'http://{apiUrl}',headers: { 
    'auth-token': '{...}'
  }
};

await axios(config)
.then(function (response) {
  let res = JSON.stringify(response.data)
  context.log(res);
  return res;
})
.catch(function (error) {
  context.log(error);
});

}

为了以防万一,这是我的 function.json 文件

{
  "bindings": [
    {
      "authLevel": "anonymous","type": "httpTrigger","direction": "in","name": "req","methods": [
        "get"
      ]
    },{
      "type": "http","direction": "out","name": "res"
    }
  ]
}

正如我所说,当我在本地运行 azure 函数时,context.log 在 VSCode 的终端中显示数据,所以我一直在假设它也返回数据的情况下进行操作 - 但现在我不确定。

您能提供的任何指导将不胜感激,我觉得我必须非常接近,但有些配置不太正确。提前致谢!

解决方法

关于问题,请参考以下代码

我的函数应用代码

const axios = require('axios');

module.exports = async function (context,req) {
    context.log('JavaScript HTTP trigger function processed a request.');

    var config = {
        method: 'get',url: '',headers: { }
        };
    try{
       
        var response= await axios(config)
        const data=JSON.stringify(response.data)               
        context.res = {
            headers: {
                'Content-Type': 'application/json'
            },body: data
        }
    }catch(err){
        context.log(err)
        throw err
    }


}

HTML

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>API</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(document).ready(function () {
    $("#submit").click(function (e) {
       
       
            $.ajax({
                type: "GET",url: "",dataType: "json",success: function (respData,status,xhr) {
                    console.log(respData)
                   
                    #process data and show data
                },error: function (xhr,error) {
                    alert("Result: " + status + " " + error + " " + xhr.status + " " + xhr.statusText)
                }
            });
        
    });
  
    
});
</script>
</head>
 
<body>

  
<button id="submit">Call API</button>
<div id="message"></div>
</body>
 
</html>

测试 enter image description here