如何返回Azure函数的结果

时间:2018-02-08 19:06:27

标签: javascript node.js azure azure-functions

我从Azure Functions开始。我有以下代码:

module.exports = function (context, req) 
    {
        context.log('JavaScript HTTP trigger function processed a request.');

        context.log(context.req.body.videoId)
        if (context.req.body.videoId =! null) 
        {
            context.log('inicia a obtener comentarios')

             const fetchComments = require('youtube-comments-task')

            fetchComments(req.body.videoId)
            .fork(e => context.log('ERROR', e), p => {                   
                        context.log('comments', p.comments)
                        })        

             context.res = { body: fetchComments.comments }
        }
        else {
            context.res = {
                status: 400,
                body: "Please pass a videoId on the query string or in the   request body"
            };
        }
        context.done();
};

如何返回fetchComments返回的JSON?

1 个答案:

答案 0 :(得分:4)

移动分配context.res并致电context.done以承诺回拨。在标题中将Content-Type设置为application/json。基于您的代码,如

if (context.req.body.videoId =! null) {
  context.log('inicia a obtener comentarios')
  const fetchComments = require('youtube-comments-task')

  fetchComments(req.body.videoId)
    .fork(e => context.log('ERROR', e), p => {                   
       context.log('comments', p.comments);
       context.res = { 
         headers: { 'Content-Type': 'application/json' },
         body: p.comments 
       };
       context.done();
    });
}
else {
  context.res = {
    status: 400,
    body: "Please pass a videoId on the query string or in the request body"
  };
  context.done();
}