我正在建立一个nodejs / expressjs应用程序,这是我的架构: +路线 - candidate.js - index.js +意见 - layout.vash - register.vash - server.js
在我的server.js文件中,我将此代码用于管理路由:
var routes = require('./routes/index');
var candidate = require('./routes/candidate');
app.use('/', routes);
app.use('/candidate', candidate);
在candidate.js中,所有获取请求都正常,但是在帖子请求中存在问题,它无法解决路径:无法POST / caregister
var routes = require('./routes/index');
var candidate = require('./routes/candidate');
var employer = require('./routes/employer');
var app = express();
app.set('view engine', 'vash');
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended : false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, "public")));
app.use('/', routes);
app.use('/candidate', candidate);
app.use('/employer', employer);
app.set('port', (process.env.PORT || 3000));
app.listen(app.get('port'), function(){
console.log('server is listening to ' + app.get('port'));
});
var express = require('express');
var router = express.Router();
router.get('/', function(req, res){
res.render('index');
});
module.exports = router;
var express = require('express');
var router = express.Router();
var Candidate = require("../models/candidate");
router.get('/', function(req, res){
res.render('candidatelogin'); // relative to candidatelogin.vash
});
router.post('/caregister', function(req, res){
var username = req.body.username;
var email = req.body.email;
var password = req.body.password;
var passwordConf = req.body.passwordConf;
console.log(username + " " + email);
});
module.exports = router;
@html.extend('layout', function(model){
@html.block('body', function(model){
<h1>Jobseeker</h>
<div id="register">
<h3>Create new Account</h3>
<form method="post" action="/caregister">
<input type="text" name="username" placeholder="username"><br/><br/>
<input type="text" name="email" placeholder="email"><br/><br/>
<input type="password" name="password" placeholder="password"><br/><br/>
<input type="password" name="passwordConf" placeholder="password confirmation"><br/><br/>
<input type="submit" value="Register">
</form>
</div>
})
})
答案 0 :(得分:1)
使用app.use
并包含类似candidate
的前缀时,这意味着您应该稍后使用此前缀来访问此路由。
因此,candidatelogin.vash
中的表单应发布到/candidate/caregister
网址:
<div id="register">
<h3>Create new Account</h3>
<form method="post" action="/candidate/caregister">
<input type="text" name="username" placeholder="username"><br/><br/>
<input type="text" name="email" placeholder="email"><br/><br/>
<input type="password" name="password" placeholder="password"><br/><br/>
<input type="password" name="passwordConf" placeholder="password confirmation"><br/><br/>
<input type="submit" value="Register">
</form>
</div>