gpt4 book ai didi

javascript - 如何在 express 中路由 CRUD 操作?

转载 作者:行者123 更新时间:2023-11-29 21:31:46 27 4
gpt4 key购买 nike

我有以下用于 node.js、express 和使用 mongoose 的 MongoDB 连接的代码。

首先,我尝试了一个名为 server.js 的文件,它在没有 express 的情况下工作。但是现在我想用 express 来做,但它不起作用。

这只是一个在 mongo 数据库中读取和创建示例 Bear 对象的简单程序。

这是我的app.js

var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

//var routes = require('./routes/index');
var users = require('./routes/users');
var mongoose = require('mongoose');
var db = mongoose.connect('localhost:27017/nodetest1');

//var Bear = require('./routes/users');


var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

var port = process.env.PORT || 8080;

// Make our db accessible to our router
app.use(function(req,res,next){
req.db = db;
next();
});

// ROUTES FOR OUR API
// =============================================================================
var router = express.Router(); // get an instance of the express Router

router.use(function(req,res,next){
console.log('something is happening');
next();
});

// test route to make sure everything is working (accessed at GET http://localhost:8080/api)
router.get('/', function(req, res) {
res.json({ message: 'hooray! welcome to our api!' });
});

// more routes for our API will happen here




// REGISTER OUR ROUTES -------------------------------
// all of our routes will be prefixed with /api

app.use('/', router);
app.use('/bears', users);

// START THE SERVER
// =============================================================================
app.listen(port);
console.log('Magic happens on port ' + port);


// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});


module.exports = app;

这是我的 users.js

var express = require('express');
var router = express.Router();

var Schema = mongoose.Schema;

var BearSchema = new Schema({
name: String
});

module.exports = mongoose.model('Bear',BearSchema);


router.route('/bears')

// create a bear (accessed at POST http://localhost:8080/api/bears)
.post(function(req, res) {

var bear = new Bear(); // create a new instance of the Bear model
bear.name = req.body.name; // set the bears name (comes from the request)

// save the bear and check for errors
bear.save(function(err) {
if (err)
res.send(err);

res.json({ message: 'Bear created!' });
});

});
module.exports = router;

请告诉我如何路由 CRUD 操作。

最佳答案

你不能在一个文件中有两个 module.exports。位于文件底部的那个会重写所有其他的。

你需要两个文件,比如

controllers/users.js

var express = require('express');
var router = express.Router();

router.route('/bears')

// create a bear (accessed at POST http://localhost:8080/api/bears)
.post(function(req, res) {

var bear = new Bear(); // create a new instance of the Bear model
bear.name = req.body.name; // set the bears name (comes from the request)

// save the bear and check for errors
bear.save(function(err) {
if (err)
res.send(err);

res.json({ message: 'Bear created!' });
});

});
module.exports = router;

模型/user.js

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var BearSchema = new Schema({
name: String
});

module.exports = mongoose.model('Bear',BearSchema);

在您的 app.js 中,您可以这样做:

var user = require('controllers/user');
app.use('/users', user);

它的端点现在监听在 /users/bears

如果你在某处需要你的模型,只需加载它

var userModel = mongoose.model('User');

我建议下载并运行这个 template , 添加新功能更容易,当你看到它们是如何实现的

关于javascript - 如何在 express 中路由 CRUD 操作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36128281/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com