node.js Express 创建RESTful API

0.项目机构

1.package.js 安装mongoose依赖和body-parser依赖

{
  "name": "test",
  "version": "0.0.0",
  "private": true,
  "scripts": {
    "start": "node ./bin/www"
  },
  "dependencies": {
    "body-parser": "^1.18.3",
    "cookie-parser": "~1.4.3",
    "debug": "~2.6.9",
    "express": "~4.16.0",
    "http-errors": "~1.6.2",
    "mongoose": "^5.1.6",
    "morgan": "~1.9.0",
    "pug": "2.0.0-beta11"
  }
}
npm install mongoose --save
npm install body-parser --save

2. app.js 加数据库连接,还有router

这边在mongodb中创建了一个xiaohua1的database

var mongoose = require('mongoose');

mongoose.connect('mongodb://article:123456@localhost:27017/xiaohua1')

var apiRouter = require('./routes/api')

app.use('/api', apiRouter)

3.models/xiaohua.js

var mongoose = require('mongoose');

var Schema = mongoose.Schema;

var XiaohuaSchema = new Schema({
    title : String
})


module.exports = mongoose.model('Xiaohua', XiaohuaSchema)

4.routes/api.js

RouteHTTP VerbDescription
/api/xiaohuasGETGet all the xiaohuas.
/api/xiaohuasPOSTCreate a xiaohua.
/api/xiaohuas/:xiaohua_idGETGet a single xiaohua.
/api/xiaohuas/:xiaohua_idPUTUpdate a xiaohua with new info.
/api/xiaohuas/:xiaohua_idDELETEDelete a xiaohua.
var express = require('express');
var router = express.Router();



var Xiaohua = require('../models/xiaohua')


// middleware to use for all requests
router.use(function(req, res, next) {
    // do logging
    console.log('Something is happening.');
    next(); // make sure we go to the next routes and don't stop here
});
/* GET home page. */
router.get('/', function(req, res, next) {
    res.json({ message: 'hooray! welcome to our api!' });
});



router.route('/xiaohuas')

    .post(function(req, res) {

        var xiao = new Xiaohua();
        xiao.title = req.body.title;

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

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

    })

    .get(function(req, res) {
        Xiaohua.find(function(err, xiaohuas) {
            if (err)
                res.send(err);

            res.json(xiaohuas);
        });
    });





router.route('/xiaohuas/:xiaohua_id')

    .get(function(req, res) {
        Xiaohua.findById(req.params.xiaohua_id, function(err, xiaohua) {
            if (err)
                res.send(err);
            res.json(xiaohua);
        });
    })

    .put(function(req, res) {

        // use our bear model to find the bear we want
        Xiaohua.findById(req.params.xiaohua_id, function(err, xiaohua) {

            if (err)
                res.send(err);

            xiaohua.title = req.body.title;

            // save the xiaohua
            xiaohua.save(function(err) {
                if (err)
                    res.send(err);

                res.json({ message: 'Xiaohua updated!' });
            });

        });
    })


    .delete(function(req, res) {
        Xiaohua.remove({
            _id: req.params.xiaohua_id
        }, function(err, xiaohua) {
            if (err)
                res.send(err);

            res.json({ message: 'Successfully deleted' });
        });
    });

module.exports = router;

http://www.waitingfy.com/archives/4446

4446

Leave a Reply

Name and Email Address are required fields.
Your email will not be published or shared with third parties.