如何解决对 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>
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>
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。