0

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

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

4

1 回答 1

0

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

我的函数应用代码

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>

测试 在此处输入图像描述

于 2021-05-17T02:34:59.020 回答