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

我最近在使用 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。


汪汪一只猫
浏览 91回答 1
1回答

阿波罗的战车

该函数可能试图req从其this上下文中获取。但是您没有传递带有上下文的函数。更改此行:return&nbsp;acceptFunction(opts.acceptedTypes);到:return&nbsp;acceptFunction.call(req,&nbsp;opts.acceptedTypes);该call()方法的第一个参数是应该this在被调用函数中使用的对象。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript