我正在使用快递js。我想访问server.js中的其他文件js函数。请任何人帮助我。
server.js
var express = require('express'),
path = require('path'),
cors = require('cors'),
bodyParser = require('body-parser'),
routes = require('#######'), //web routes
connection = require("######"); //mongodb connection
authChecker = require("./###/authChecker");
var app = express();
app.use(bodyParser.json());
app.use(express.static(path.join(__dirname, 'app')));
app.use(express.static('node_modules'));
app.use(cors());
app.use(authChecker);
app.use('/', routes);
我的authChecker js文件是
authChecker.js
module.exports = {
function(req, res, next) {
console.log("authondication checker process");
if (req.session.auth || req.path === '/auth') {
next();
} else {
res.redirect("/auth");
}
}
}
当app.use(authChecker)执行此行时,会在服务器启动时显示此错误。
E:\MEAN_STACK\MySampAps\Crud_samp\node_modules\express\lib\application.js:210
throw new TypeError('app.use() requires middleware functions');
^
TypeError: app.use() requires middleware functions
at Function.use (E:\MEAN_STACK\MySampAps\Crud_samp\node_modules\express\lib\application.js:210:11)
at Object.<anonymous> (E:\MEAN_STACK\MySampAps\Crud_samp\server.js:39:5)
at Module._compile (module.js:569:30)
at Object.Module._extensions..js (module.js:580:10)
at Module.load (module.js:503:32)
答案 0 :(得分:2)
您可以将 authChecker.js 修改为:
module.exports = function(req, res, next) {
console.log("authondication checker process");
if (req.session.auth || req.path === '/auth') {
next();
} else {
res.redirect("/auth");
}}
然后你可以在 server.js 中调用该函数:app.use(authChecker)
希望这有帮助
答案 1 :(得分:1)
检查一下 server.js
var express = require('express'),
path = require('path'),
cors = require('cors'),
bodyParser = require('body-parser'),
routes = require('#######'), //web routes
connection = require("######"); //mongodb connection
authChecker = require("./###/authChecker").auth;
var app = express();
app.use(bodyParser.json());
app.use(express.static(path.join(__dirname, 'app')));
app.use(express.static('node_modules'));
app.use(cors());
app.use(authChecker);
app.use('/', routes);
我的authChecker js文件是
authChecker.js
module.exports = {
auth:function(req, res, next) {
console.log("authondication checker process");
if (req.session.auth || req.path === '/auth') {
next();
} else {
res.redirect("/auth");
}
}
}