gpt4 book ai didi

javascript - 如何在 Node js 中返回对 REST api 的响应

转载 作者:行者123 更新时间:2023-12-01 03:11:24 33 4
gpt4 key购买 nike

我是 Node JS 新手。我的 Node js REST api 路由代码是:

'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 函数是:

'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 函数捕获结果数据,也无法将其作为响应发送。请帮助我!!!

最佳答案

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

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

需要异步处理,例如:

'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 处理 Node 中的异步调用的非常基本的示例。你应该研究一下它是如何工作的。例如,您可以通过阅读以下内容开始:https://www.promisejs.org/

关于javascript - 如何在 Node js 中返回对 REST api 的响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45815209/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com