为了账号安全,请及时绑定邮箱和手机立即绑定

在嵌套函数中使用 req.accept 时 req 未定义

在嵌套函数中使用 req.accept 时 req 未定义

汪汪一只猫 2023-01-06 09:32:49
我最近在使用 express中的内置 、 、 和 函数时遇到了req.accepts一个 req.acceptsLanguages问题req.acceptsCharsets。req.acceptsEncodings我有一个像这样的快速中间件功能:function acceptCheckpoint(acceptOpts) {  // Calling the following function results in a TypeError.  function checkAccept(req, res, opts) {    let acceptFunction = null;    switch (opts.whichAccept) {    case "type":      acceptFunction = req.accepts;      break;    case "lang":      acceptFunction = req.acceptsLanguages;      break;    case "charset":      acceptFunction = req.acceptsCharsets;      break;    case "encoding":      acceptFunction = req.acceptsEncodings;      break;    default:      acceptFunction = req.accepts;      break;    }    return acceptFunction(opts.acceptedTypes);  }  return (req, res, next) => {    const accepted = [];    Object.getOwnPropertyNames(acceptOpts).forEach(key => {      if (key === "ignoreAcceptMismatch") { return; }      const acceptsType = checkAccept(req, res, {        whichAccept: key,        acceptedTypes: acceptOpts[key]      });      accepted.push(acceptsType);    });    if (accepted.some(type => !type) && !acceptOpts.ignoreAcceptMismatch) {      res.type("html");      res.status(406);      res.send("<h1>406 Not Acceptable.</h1>");      return;    }    next();  };}问题是,当我在主函数 ( ) 中使用req.accepts或其中一个函数时,如下所示:.acceptsacceptCheckpoint// Pretend we're in acceptCheckpoint...// This works.accepted.push(req.accepts("html"));有用。而且,当我req在这些函数中的任何一个中记录对象时,它都会返回预期值。我还尝试将req对象记录request.js到 express 模块的文件中,然后它返回了undefined. 所以这让我相信这是表达本身的问题。我尝试删除 package-lock.json 和 node_modules,然后运行npm install. 没修好。是的,我正确地调用了 express 中间件函数。知道为什么会这样吗?我使用的是 express v4.17.1、Node.JS v12.18.1 和 NPM v6.14.5。
查看完整描述

1 回答

?
阿波罗的战车

TA贡献1862条经验 获得超6个赞

该函数可能试图req从其this上下文中获取。但是您没有传递带有上下文的函数。

更改此行:

return acceptFunction(opts.acceptedTypes);

到:

return acceptFunction.call(req, opts.acceptedTypes);

call()方法的第一个参数是应该this在被调用函数中使用的对象。


查看完整回答
反对 回复 2023-01-06
  • 1 回答
  • 0 关注
  • 89 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信