如何在节点js中返回对REST api的响应 [英] how to return response to REST api in node js

查看:159
本文介绍了如何在节点js中返回对REST api的响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Node JS的新手.我的节点js REST api路由代码为:

I'm new to Node JS. My node js REST api route code is:

'use strict';
module.exports = function(app) {
    var sequel = require('../controllers/sampleController');
    app.get('/task?:email', function(req, res){
        res.send(sequel.listByEmail(req.query.email));
    });
};

我的listByEmail函数是:

And my listByEmail function is:

'use strict';
var apiKey = '1xxxxxxxxL';
exports.listByEmail = function(emailid) {
    console.log(emailid);
    if(emailid != null && emailid != undefined) {
        var xyz = require("xyz-api")(apiKey);
        xyz.person.findByEmail(emailid, function(err, data) {
            if(data.status == 200){
                return data; // data is in json format
            }
        });
    }
};

我从该listbyemail函数返回了这样的数据.数据在那里,如果我尝试在控制台中打印数据,它会出现.但是在返回数据时,它不会返回.它总是返回未定义的.我无法从路由中的listByEmail函数捕获结果数据,也无法将其作为响应发送.请帮助我!!!

I returned data like this from that listbyemail function. Data is there, if i try to print the data in console it appears. But while returning the data, it won't returned. It's always return undefined. I can't able to catch the result data from listByEmail function in route and not able to send it as response. Please helpMe!!!

推荐答案

在ListByEmail函数中,您正在调用异步方法 findByEmail .

In your ListByEmail function you are calling an asynchronous method, findByEmail.

到达 return data; 行时,您的listByEmail函数已经返回,因此您不会向调用者返回任何内容.

When you reach the return data; line, your listByEmail function already returned so you are not returning anything to the caller.

您需要异步处理它,例如:

You need to handle it asynchronously, for example:

'use strict';
var apiKey = '1xxxxxxxxL';
exports.listByEmail = function(emailid) {
    return new Promise(function(resolve, reject) {
        console.log(emailid);
        if(emailid != null && emailid != undefined) {
            var xyz = require("xyz-api")(apiKey);
            xyz.person.findByEmail(emailid, function(err, data) {
                if(data.status == 200){
                    resolve(data); // data is in json format
                }
            });
        } else {
            reject("Invalid input");
        }
    };

然后:

'use strict';
module.exports = function(app) {
    var sequel = require('../controllers/sampleController');
    app.get('/task?:email', function(req, res){
        sequel.listByEmail(req.query.email).then(function(data) {
            res.send(data);
        });
    });
};

这是使用 Promise 处理节点中的异步调用的非常基本的示例.您应该研究一下它是如何工作的.例如,您可以通过阅读以下内容开始: https://www.promisejs.org/

This is a very basic example of using Promise to handle asynchronous calls in node. You should study a little bit how this works. You can start for example by reading this: https://www.promisejs.org/

这篇关于如何在节点js中返回对REST api的响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆