gpt4 book ai didi

javascript - 我什么时候应该在 javascript 中的 require ('module' ) 之后使用点 (.)

转载 作者:行者123 更新时间:2023-11-28 17:29:48 26 4
gpt4 key购买 nike

我有这个身份验证中间件,并且我导出了这个

var {User} = require('./../model/user');

var authenticate = (req, res, next) => {
var token = req.header('x-auth');
User.findByToken(token).then((user) => {
if (!user) return Promise.reject();
req.user = user;
req.token = token;
next();
}).catch((err) => res.status(401).send());
}

module.exports = {authenticate};

在 server.js 中varauthenticate = require('./middleware/authenticate')没用。

为什么我需要添加这个

var verify = require('./middleware/authenticate').authenticate;

如果我在 require 之后没有添加 .authenticate ,则会将错误记录为

Route.get() requires a callback function but got a [object Object]

最佳答案

模块是 Javascript 代码结构的基本构建 block 。您可以使用它们来构建您的代码。当你写

module.exports = someobject

您实际上是在为模块的客户端定义一个公共(public)接口(interface)。

现在考虑上面的陈述,它基本上有两个部分:-
1)有一个变量名称(左侧)
2)有一个物体。 (右侧)

您的语句只是将一个对象与一个变量名称关联起来。您可以使用此语句将任何内容与变量 (module.exports) 关联。

现在让我们来解决你的问题

 //authenticate.js
// some code
module.exports = {authenticate}; // your interface is pointing to an object

//server.js

var authenticate = require('./middleware/authenticate');

/* after this statement your module.exports is pointing to {authenticate} object which is not a callable.
You actually wants to access the the authenticate function which lies inside /this object therefore when you do*/


var authenticate = require('./middleware/authenticate').authenticate
// it works because you are now accessing the function inside the object which is callable.

关于javascript - 我什么时候应该在 javascript 中的 require ('module' ) 之后使用点 (.),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50733586/

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