我正在尝试对 azure 函数进行 ajax 调用,该函数将数据保存到 azure 门户上的 cosmos db。
不起作用:
var dataArray = {
task:"abcd",
name:"efg",
dDoB:"20/12/2018",
dCountry:"America"
};
$.post('https://functionget.azurewebsites.net/api/***/code**', dataArray ,
function(data,status) {
alert("Data: " + data + "\nStatus: " + status);
});
作品:
var dataArray = {
task:"abcd",
name:"efg",
dDoB:"20/12/2018",
dCountry:"America"
};
$.get('https://functionget.azurewebsites.net/api/***/code**', dataArray ,
function(data,status) {
alert("Data: " + data + "\nStatus: " + status);
});
这是我的 azure 函数代码:
module.exports = 异步函数(上下文,req){
// We need both name and task parameters.
if (req.query.name && req.query.task) {
// Set the output binding data from the query object.
context.bindings.taskDocument = req.query;
// Success.
context.res = {
status: 200
};
}
else {
context.res = {
status: 400,
body: "The query options 'name' and 'task' are required"
};
}
};
当我们在控制台中查找请求的网络时,GET 在查询字符串中发送参数并在表单数据中发送参数。有人可以让我知道如何通过 ajax 调用将带有参数的 post 调用发送到 azure 函数。谢谢前进!</p>
最佳答案
Ajax 将 dataArray
作为表单数据而不是查询字符串,因此使用 req.query.xx
我们无法按预期接收数据。我们可以发布一个 Json 并读取 req.body
。检查下面的代码。
对于函数,将 query
更改为 body
。
if (req.body.name && req.body.task) {
context.bindings.taskDocument = req.body;
...
}
对于ajax,使用$.ajax
而不是$.post
发送Json。
$.ajax({
type: "POST",
url: "<functionurl>",
data: JSON.stringify(dataArray),
contentType: "application/json; charset=utf-8",
success: function(data,status) {
alert("Data: " + data + "\nStatus: " + status);
}
});
关于Azure函数后调用导致使用ajax调用产生400错误请求,并且当POST更改为GET时相同的函数可以工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53940854/