Node JS API: Return JSON to user, after service is done.

老子叫甜甜 提交于 2019-12-13 07:47:07

问题


I'm currently using node.js to create a post-upload API, to upload an image, which is processed by the Watson Visual Recognition Service. This returns a JSON, which is currently logged to the console. Is there a way to send this JSON back to the user, after the process is done? I'm a total newbie to Node.js, so I really appreciate your help.

This is my code:

// initialising ...  

app.post( '/detectFaces', avatarUpload, ( req, res ) => { 

    avatarUpload( req, res, ( err ) => {

        if ( err || !req.file )
            return res.send({ error: 'invalid_file' })

        console.log( req.file );

        var path = req.file.path;
        var name = req.file.filename;  

        var params = { 
            images_file: fs.createReadStream(path)
        };   

        //Call to the visual recognition Service
        visual_recognition.detectFaces(params, function(err, res){ 
            if(err) 
                console.log(err); 
            else  
                console.log(JSON.stringify(res, null, 2));   

        });  

        //The JSON of the visual Rec Service should send here. 
        res.send({ 'status' : 'check', url: 'uploads' + '/' + filename }) 


    }) 
    var params = { 
            images_file: fs.createReadStream(path)
        };    


}); 


app.listen(3000, function () {
  console.log('Upload Server listening on port 3000');
});

回答1:


You can use this

visual_recognition.detectFaces(params, function(err, result){ 
    if(err) 
        console.log(err); 
    else  
        res.status(200).json(result)   
}); 


来源:https://stackoverflow.com/questions/42222036/node-js-api-return-json-to-user-after-service-is-done

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!