【问题标题】:Azure function not returning resultAzure函数不返回结果
【发布时间】:2020-03-09 19:03:46
【问题描述】:

我正在关注tutorial,我可以从控制台中的console.log(result) 看到正确的结果,但是当我从邮递员发出 GET 请求时,它什么也没返回。为什么是send(200, JSON.parse(JSON.stringify(result))); 不工作?

我还做了一个console.log(JSON.parse(JSON.stringify(result))),它正确地将数据正确返回到控制台。只是由于某种原因无法发送响应。

var MongoClient = require('mongodb').MongoClient;
var Post = require('./model/post');

module.exports = async function (context, req) {

  let currentPage = 1;
  context.log("process.env.CosmosDBConnectionString");
  context.log(process.env.CosmosDBConnectionString);

  MongoClient.connect(process.env.CosmosDBConnectionString, (err, client) => {

    let send = response(client, context);

    if (err) send(500, err.message);


    console.log("DBNAME: " + process.env.dbName);
    let db = client.db(process.env.dbName);

    let queryDate = Date.now();


    db.collection('listings').find({}) //test

      .toArray((err, result) => {
        console.log(result);
        if (err) send(500, err.message);
        send(200, JSON.parse(JSON.stringify(result)));

      });
  });




};

function response(client, context) {
  return function (status, body) {
    context.res = {
      status: status,
      body: body
    };

    client.close();
    context.done();
  };
}

【问题讨论】:

    标签: node.js mongodb azure mongoose azure-functions


    【解决方案1】:

    我不确定在这种情况下“发送”功能会做什么,但我认为如果您将其更改为以下内容应该可以:

    db.collection('listings').find({}) //test
    .toArray((err, result) => {
        console.log(result);
        if (err)
        {
            context.res = { status: 500, body: err.message }; 
        }
        else 
        {
            context.res = { status: 200, body: JSON.parse(JSON.stringify(result)) }; 
        }
        context.done();
    });
    

    【讨论】:

    • 随着您更新的更改,它仍然返回空白。更新代码:pastebin.com/dnEGuhyH我看到配置的邮递员唯一的内容类型为application/x-www-form-urlencoded 没有设置参数或任何东西。 console.log 数据也显示状态 200
    • 另一件事是,如果我在 else 语句分配之后执行console.log(context.res),它也会在那里输出数据。邮递员也返回 200 postimg.cc/r0H5QL98
    • 尝试从 module.exports = async function (context, req) { 中移除异步
    • 就是这样!邮递员现在工作。我以为我必须使用异步,因为模板使用它。谢谢!我还尝试了send(200... 的方式,我从我从教程中学到的问题中构建了它,这也很有效。我想知道那个发送功能是从哪里来的。我想也许它以某种方式内置于天蓝色功能?
    • 在文档中有 context.res.send。也许它是一种合成糖...docs.microsoft.com/en-us/azure/azure-functions/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-12-27
    • 2012-12-27
    • 2020-07-04
    • 1970-01-01
    • 2019-08-13
    • 1970-01-01
    相关资源
    最近更新 更多