gpt4 book ai didi

javascript - Node/Express 路由不等待 Redis 服务器回调

转载 作者:可可西里 更新时间:2023-11-01 11:33:34 24 4
gpt4 key购买 nike

需要对下面的代码进行哪些具体更改,以便在对 Redis 客户端进行任何打开调用之前不发送 res.json(...) 命令.somecommand(..) 返回了吗?

下面的代码抛出与 client.hmset(uname, { ... } 试图在 res.json(...)< 之后设置响应 header 相关的错误 被调用。当我将 return res.json() 命令移动到 client.exists(uname, function(err, reply) { ... } 条件 block ,而不是它们在 block 内的当前位置,anonymous token 值被发送到客户端应用程序,而不是生成的 token value,表示Redis服务器的回调没有返回。

如何更改下面的代码,以便在返回 Redis 服务器回调之前,res.json( ... ) 命令无法运行?理想情况下,如果 Redis 服务器回调花费的时间太长,将有一些条件在发送错误消息之前等待一定时间。

通过在文件顶部添加以下两行,将 Redis 添加到包含以下所有代码的 routes.js 文件中:

var redis = require('redis');
var client = redis.createClient();

下面是在代码中对Redis服务器的各种调用:

client.exists(uname, function(err, reply) { ... }
client.hgetall(uname, function(err, object) { ... }
client.hmset(uname, { ... }
client.expire(uname, 10);

Node.js/Express.js API 路由的完整代码为:

app.get('/user**', function(req, res) {
console.log("You Hit The User Route TOP");
request({
method: 'GET',
url: authServer + '/uaa/user',
json: true,
auth: {
user: null,
password: null,
sendImmediately: true,
bearer: bearerToken
}
}, function (error, response, body) {
if(error){
console.log('ERROR with user request.');
return res.sendStatus(500);
}
else {
var uname = '';var jwtUser = 'empty';var jwtJSON = { "token" : "anonymous" }
console.log(response.statusCode);
if(body['name']){
uname = body['name'];console.log('uname is: ');console.log(uname);
if(uname.length > 0) {
scopesLocal = body['oauth2Request'].scope.toString();
client.exists(uname, function(err, reply) {//Check to see if a Redis key for the user already exists
if (reply === 1) {//a redis key DOES exist
console.log('\"'+uname+'\" exists');
client.hgetall(uname, function(err, object) {//retrieve all the values in the hash/object that we just set
if(object) {
if(object["jwt"]) {
console.log('object[\"jwt\"] is: ');console.log(object["jwt"]);
jwtJSON = { "token" : object["jwt"] };
console.log('jwtJSON is: ');console.log(jwtJSON);
return res.json(jwtJSON);
}
}
});
} else {//a redis key DOES NOT exist
console.log('\"'+uname+'\" doesn\'t exist');
jwtUser = generateJwt(uname, authoritiesLocal);
client.hmset(uname, {//store a hash/object
'AccessToken': body['details'].tokenValue,
'TokenType': body['details'].tokenType,
'Authenticated': body['authenticated'],
'Principal': body['principal'],
'Scopes': scopesLocal.toString(),
'Authorities' : authoritiesLocal,
'jwt' : jwtUser
});
jwtJSON = { "token" : jwtUser };console.log('jwtJSON is: ');console.log(jwtJSON);
return res.json(jwtJSON);
}
client.expire(uname, 10);//set the key to expire in 10 seconds. use this to manage session length
});//end of Redis conditional block
console.log('jwtJSON is: ');console.log(jwtJSON);
} else { console.log('uname is empty!'); }
return res.json(jwtJSON);
}
};
});
console.log("You Hit The User Route BOTTOM");
});

nodemon 终端中的错误信息是:

_http_outgoing.js:346
throw new Error('Can\'t set headers after they are sent.');
^

Error: Can't set headers after they are sent.
at ServerResponse.OutgoingMessage.setHeader (_http_outgoing.js:346:11)
at ServerResponse.header (/home/user/nodejs_apps/oauth_seed_app/node_modules/express/lib/response.js:719:10)
at ServerResponse.json (/home/user/nodejs_apps/oauth_seed_app/node_modules/express/lib/response.js:247:10)
at Command.callback (/home/user/nodejs_apps/oauth_seed_app/app/routes.js:112:44)
at normal_reply (/home/user/nodejs_apps/oauth_seed_app/node_modules/redis/index.js:714:21)
at RedisClient.return_reply (/home/user/nodejs_apps/oauth_seed_app/node_modules/redis/index.js:816:9)
at JavascriptRedisParser.Parser.returnReply (/home/user/nodejs_apps/oauth_seed_app/node_modules/redis/index.js:188:18)
at JavascriptRedisParser.execute (/home/user/nodejs_apps/oauth_seed_app/node_modules/redis-parser/lib/parser.js:413:12)
at Socket.<anonymous> (/home/user/nodejs_apps/oauth_seed_app/node_modules/redis/index.js:267:27)
at emitOne (events.js:90:13)
at Socket.emit (events.js:182:7)
at readableAddChunk (_stream_readable.js:153:18)
at Socket.Readable.push (_stream_readable.js:111:10)
at TCP.onread (net.js:534:20)

我读了this posting关于具体的错误信息。我读了this other posting关于如何等待回调。我还读了this posting关于 Redis 对 Node.js 的回调但是我看不到如何将其他帖子的答案应用于上面代码中的 Redis 回调问题。

最佳答案

问题是 OP 中的 return res.json(jwtJSON); 命令没有被分离到离散的 if...else block 中。

解决方法是:

if(something) {
//populate jwtJSON with a real JWT
return res.json(jwtJSON);
} else {
return res.json(jwtJSON);//this leaves the anonymous value
}

对上面代码中的每个嵌套条件进行这种分离就解决了这个问题。

关于javascript - Node/Express 路由不等待 Redis 服务器回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38447052/

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