gpt4 book ai didi

node.js - NodeJs 和 ExpressJs 无法分离错误和响应处理中使用的公共(public)代码

转载 作者:太空宇宙 更新时间:2023-11-04 02:17:00 25 4
gpt4 key购买 nike

我是 NodeJS 和expressJs 的新手。我有以下代码,用于获取用户列表

在下面的代码中,我想将函数(错误,响应,主体)方法中的代码分开并在不同的方法中重用

我怎样才能做到这一点?我在所有方法中重复使用这些,因此我想将其分开并在所有地方重用。

router.get('/details/*******/all', function(req, res, next) {
var cookie = request.cookie("JSESSIONID=" + req.cookies.JSESSIONID);
jar.setCookie(cookie, LIST_OF_STAFF, function(error, cookie) {});
request({
url: LIST_OF_STAFF,
method: "GET",
jar: jar,
headers: headers
}, function(error, response, body) {
if (!error && response.statusCode === 400 && !_.isUndefined(body)) {
res.status(400)
res.json(body);
} else
if (!error && response.statusCode === 401 && !_.isUndefined(body)) {
res.status(401)
res.json(body);
} else
if (!error && response.statusCode === 200 && !_.isUndefined(body)) {
res.json(JSON.parse(body));
} else {
next(error);
}
});
});

最佳答案

您可以将函数移动到另一个位置,并为其命名。然后您可以重复使用它。

例如,它是如何使用的:

router.get('/details/*******/all', function(req, res, next) {
var cookie = request.cookie("JSESSIONID=" + req.cookies.JSESSIONID);
jar.setCookie(cookie, LIST_OF_STAFF, function(error, cookie) {});
request({
url: LIST_OF_STAFF,
method: "GET",
jar: jar,
headers: headers
}, newFunction.bind(null,res);
});

function newFunction (res,error, response, body) {
// You can use res (res.write)
if (!error && response.statusCode === 400 && !_.isUndefined(body)) {
res.status(400)
res.json(body);
} else
if (!error && response.statusCode === 401 && !_.isUndefined(body)) {
res.status(401)
res.json(body);
} else
if (!error && response.statusCode === 200 && !_.isUndefined(body)) {
res.json(JSON.parse(body));
} else {
next(error);
}
}

关于node.js - NodeJs 和 ExpressJs 无法分离错误和响应处理中使用的公共(public)代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35269706/

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