如何返回Azure函数的结果

Chr*_*lez 2 javascript azure node.js azure-functions

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

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();
};
Run Code Online (Sandbox Code Playgroud)

如何返回fetchComments返回的JSON?

Mik*_*kov 5

移动分配context.res并调用context.done到Promise回调。设置Content-Typeapplication/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();
}
Run Code Online (Sandbox Code Playgroud)