我最近遇到了这段代码,我不明白为什么next
从protect
函数中被省略了(在protectandauth
函数中(,而它最初包含在protect
函数中。我想知道protect=async(req,res,next)
和protect=async(req,res,()=>{}
之间的区别。
我还看到,即使protect
(protectandauth
内部的那个(函数中省略了next
,它仍然在"if"语句之后的代码中使用,这怎么可能呢?
代码:
export const protect = async (req, res, next) => {
if (
req.headers.authorization &&
req.headers.authorization.startsWith("Bearer")
) {
let token;
token = req.headers.authorization.split(" ")[1];
const decoded = jwt.verify(token, "kris");
req.userId = decoded.id;
try {
req.user = await User.findById(req.userId).select("-password");
next();
} catch (error) {
res.status(401).json(error.message);
}
if (!token) {
res.status(404).json("no token found");
}
}
};
export const protectandauth = async (req, res, next) => {
protect(req, res, () => {
if (req.userId == req.params.id) {
next();
} else {
res.status(401).json("not authorised");
}
});
};
每次回调访问req
和res
时,也可以访问next
。CCD_ 13是一个用来表示";传递到下一个回调";,知道一个请求可以由多个回调处理,比如
const firstCallback= (req, res, next) => {}
const secondCallback= (req, res, next) => {}
app.get("/", firstCallback);
app.get("/", secondCallback);
// or using this syntax
app.get("/", firstCallback, secondCallback);
在上面的例子中,当请求到达/
时,它首先由firstCallback
处理,这是以下两种情况之一(否则请求将挂起,用户将不会得到响应(:
- 它通过调用
res
方法之一(如res.status(401).json("not authorised");
(来停止请求 - 上面写着";传递到下一个回调";调用
next()
,然后由secondCallback
进行处理
如果参数中省略了next
,那么您将调用next()
,其中它是undefined
,这将引发一个错误。说到protect
函数的使用,如果你注意到,next
是protectandauth
参数的一部分,而next
是在protect
的第三个参数中使用的,即:
() => {
if (req.userId == req.params.id) {
next();
} else {
res.status(401).json("not authorised");
}
}
在这个特定的代码中,上面的函数在protect
的定义中作为next
传递。
如果我们想将请求传递给下一个中间件,我们将使用next。也许在protect中,程序员可能不想将req传递给下一个中间件,但在protectandauth中,如果这个条件是真的,他希望将req传给下一个子中间件
if (req.userId == req.params.id) {
next();
}