(本文爲課程筆記)
首先新建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裏測試了。