我在集成PassportJS时遇到了一些问题 - 我在req.url未定义时遇到错误。 我认为这与我如何路由文件有关,但我不知道为什么。这是我得到的错误,当我将护照添加到我的路线时会发生:
/Users/Mahraan/this_project/node_modules/express/lib/router/index.js:128
var search = 1 + req.url.indexOf('?');
^
TypeError: Cannot read property 'indexOf' of undefined
at Function.proto.handle (/Users/Mahraan/this_project/node_modules/express/lib/router/index.js:128:27)
at router (/Users/Mahraan/this_project/node_modules/express/lib/router/index.js:34:12)
at module.exports (/Users/Mahraan/this_project/router/index.js:5:53)
at Object.<anonymous> (/Users/Mahraan/this_project/server.js:33:20)
at Module._compile (module.js:460:26)
at Object.Module._extensions..js (module.js:478:10)
at Module.load (module.js:355:32)
at Function.Module._load (module.js:310:12)
at Function.Module.runMain (module.js:501:10)
at startup (node.js:129:16)
我已将其缩小到下面的文件,但我不确定需要更改才能让它工作。
以下是相关文件
文件结构
- node_modules
- config
---- passport.js
-public
---- css
---- js
- router
---- routes
-------- app-login.js
-------- (+1 file for each route in the project)
---- index.js
- views
---- pages
-------- app-login.ejs
-------- (+1 file for each route in the project)
server.js
package.json
server.js
var express = require("express");
var passport = require('passport');
var flash = require('connect-flash');
var morgan = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var session = require('express-session');
var app = express();
var passport_config = require('./config/passport')(passport);
var port = process.env.PORT || 8080
var ip = process.env.IP || 'localhost'
app.use(morgan('dev'));
app.use(cookieParser());
app.use(bodyParser());
app.set("view engine", "ejs");
app.use(express.static(__dirname + "/public"));
// passport
app.use(session({ secret: 'supersecret' }));
app.use(passport.initialize());
app.use(passport.session());
app.use(flash());
require('./router')(app, passport);
app.listen(port, ip, function() {
console.log("Listening on http://" + ip + ":" + port + "/app");
});
路由器/ index.js
module.exports = function(app, passport){
// gives me the error
// app.use("/app/", require("./routes/app-login")(passport));
// works great
app.use("/app/", require("./routes/app-login"));
}
路由器/路由/应用-login.js
var express = require("express");
var router = express.Router();
router.get("/", function(req, res){
res.render("pages/app/app-login");
});
// what I want to implement
// router.post('/', passport.authenticate("login", function(req, res) {
// do stuff
// }));
module.exports = router;
答案 0 :(得分:2)
如果你想调用require()
的值作为你在router / index.js中的函数,你需要编写module.exports
作为一个函数来获取你想传递的参数。
因此,对于 router / routes / app-login.js ,您需要:
var express = require("express");
var router = express.Router();
module.exports = function (passport) {
router.post('/', passport.authenticate("login", function(req, res) {
// do stuff
}))
})