用MVC在node js中制作路由



我是后端编程的新手,我正试图路由我的应用程序,它是建立在nodejs和expressjs上的,但是。我首先在没有使用"路由器()"的情况下构建它,但现在我试图将它与MVC集成在一起,我遇到了一些问题。

这是一段应该路由到/storePost的代码:

…在index.js文件:

var express = require('express');
...
var adminRouter = require('./routes/admin');
var indexRouter = require('./routes/index');
app.use('/admin', adminRouter);
app.use('/', indexRouter);
...

…在admin.js文件中:

var express = require('express');
var router = express.Router();
...
var bookController = require('../controllers/bookController');
...
router.get('/createBook', bookController.book_create);
router.post('/storeBook' , bookController.book_store);
...
module.exports = router

…在bookController.js文件

var Book = require('../database/models/Book');
...
var book_store = (req, res) => {
try{
var { file } = req.files;

file.mv(path.resolve(__dirname,'public/uploads', file.name), (error) => {
console.log('File loaded to server');

Book.create({
...req.body,
file: `/books/${file.name}`
}, (error) => {
console.log(error);
res.redirect('/displayBook');
});
});   
}catch(error) {
console.log(error);
}
};
...
module.exports = {
...
book_store: book_store,
...
}

这是应用程序应该路由的少数:

@layout('layouts.admin');
@section('content')
<div class="container p-2 m-4">
<div class="row">
<div class="col-8-md offset-2">
<form class="form-signin" method="POST" action="/storeBook" enctype="multipart/form-data">
...
<button class="btn btn-primary btn-round" type="submit">Create Book</button>
</form>
</div>
</div>
</div>
<style>
</style>
<br>
<br>
@endsection

应用运行在MongoDB/mongoose上作为数据库。下面是应用程序抛出的错误:Cannot Post/storeBook.

我认为你搞错了。你应该发送POST请求到/admin/storeBook,而不是/storeBook。

您需要添加:

app.use('/admin/', adminRouter);

add/after admin

相关内容

  • 没有找到相关文章

最新更新