【问题标题】:Ajax call to Azure function returns no data对 Azure 函数的 Ajax 调用不返回数据
【发布时间】:2021-08-04 22:56:41
【问题描述】:

这是我第一次使用 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 中的终端中显示数据,所以我一直在假设它也在返回数据的情况下操作 - 但现在我不确定。

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

【问题讨论】:

    标签: javascript ajax axios azure-functions azure-http-trigger


    【解决方案1】:

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

    我的函数应用代码

    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, status, error) {
                        alert("Result: " + status + " " + error + " " + xhr.status + " " + xhr.statusText)
                    }
                });
            
        });
      
        
    });
    </script>
    </head>
     
    <body>
    
      
    <button id="submit">Call API</button>
    <div id="message"></div>
    </body>
     
    </html>
    

    测试

    【讨论】:

      猜你喜欢
      • 2014-11-12
      • 1970-01-01
      • 2011-07-06
      • 2023-04-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多