在这个简单的快递应用程序中,我对路径模块的行为很奇怪。
根页'/'有效,但我收到'/ login'的'not found'错误。但是当我执行app.get('/ login',auth)而不是app.use('/ login',auth)时它会起作用。任何帮助表示赞赏!
app.js
const express = require('express');
const app = express();
const port = process.env.PORT || 3000
const path = require("path");
const bodyParser = require('body-parser')
const mongoose = require('mongoose');
const auth = require('./routes/auth');
const index = require('./routes/index');
mongoose.connect("mongodb://localhost/dev");
// Get Mongoose to use the global promise library
mongoose.Promise = global.Promise;
//Get the default connection
var db = mongoose.connection;
//Bind connection to error event (to get notification of connection errors)
db.on('error', console.error.bind(console, 'MongoDB connection error:'));
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }));
// parse application/json
app.use(bodyParser.json());
// parse application/vnd.api+json as json
app.use(bodyParser.json({ type: 'application/vnd.api+json' }));
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));
app.use('/login', auth);
app.use('/', index);
// catch 404 and forward to error handler
app.use(function (req, res, next) {
const err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handler
app.use(function (err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error', { res : res });
});
app.listen(port);
./路由/索引
var express = require('express');
var router = express.Router();
router.get('/', function (req, res, next) {
res.render('index');
});
module.exports = router;
./路由/ AUTH
var express = require('express');
var router = express.Router();
router.get('/login', function (req, res, next) {
res.send('Hello world');
});
router.post('/login', function (req, res, next) {
res.send('Goodbye world');
});
module.exports = router;
./视图/ index.ejs
<h1>Welcome To Our App</h1>
<a href="/login">Login</a>
<a href="/user/register">Signup</a>
./视图/ login.ejs
<h1>Login</h1>
<form action="/login" method="post">
<div class="form-group">
<label>Email</label>
<input type="text" class="form-control" name="email">
</div>
<div class="form-group">
<label>Password</label>
<input type="password" class="form-control" name="password">
</div>
<button type="submit" class="btn btn-warning btn-lg">Login</button>
</form>
答案 0 :(得分:-1)
在/routes/auth.js
执行router.get('/')
而不是router.get('/login')
。
否则,您必须致电localhost/login/login
。