Express_1 Demo

(本文为课程笔记)

首先新建node.js项目,控制台输入npm init,然后按需配置即可。

然后,添加module,按需添加即可。配置完成后,package.json文件如下:

{
  "name": "webTest",
  "private": true,
  "devDependencies": {},
  "engines": {
    "node": ">=0.10.0"
  },
  "dependencies": {
    "body-parser": "^1.15.0",
    "express": "^4.13.4",
    "morgan": "^1.7.0"
  }
}

配置文件中的三个module:用express来实现server;用morgan来帮助记录日志;用body-parser来转换数据格式与编码,以便js语法兼容。

demo里所有的后台操作全部略去,用字符串叙述表示,代码如下:

var express = require('express');
var morgan = require('morgan');
var bodyParser = require('body-parser');

var hostname = 'localhost';
var port = 3000;

var app = express();
app.use(morgan('dev'));

var dishRouter = express.Router();
dishRouter.use(bodyParser.json());

dishRouter.route('/')
    .all(function (req, res, next) {
        res.writeHead(200, {
            'Content-Type': 'text/plain'
        });
        next();
    })
    .get(function (req, res, next) {
        res.end('Will send all the dishes to you!');
    })
    .post(function (req, res, next) {
        res.end('Will add the dish: ' + req.body.name + ' with details: ' + req.body.description);
    })
    .delete(function (req, res, next) {
        res.end('Deleting all dishes');
    });

dishRouter.route('/:dishId')
    .all(function (req, res, next) {
        res.writeHead(200, {
            'Content-Type': 'text/plain'
        });
        next();
    })
    .get(function (req, res, next) {
        res.end('Will send details of the dish: ' + req.params.dishId + ' to you!');
    })
    .put(function (req, res, next) {
        res.write('Updating the dish: ' + req.params.dishId + '\n');
        res.end('Will update the dish: ' + req.body.name +
            ' with details: ' + req.body.description);
    })
    .delete(function (req, res, next) {
        res.end('Deleting dish: ' + req.params.dishId);
    });

// the full path will be [ip]/dishes/[dishRouter]
app.use('/dishes', dishRouter);
// include some static resources
app.use(express.static(__dirname + '/public'));

app.listen(port, hostname, function () {
    console.log(`Server running at http://${hostname}:${port}/`);
});

在控制台输入node [文件名] 运行server,然后就可以在浏览器或者postman里测试了。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章