本文利用nodejs+restify 开发rest api,非express 等rest服务。去除了多余的模板内容。
操作步骤:
1.下载依赖:
cnpm install restify restify-plugins restify-errors --save
复制代码
2.hello-world:
/**
* Module Dependencies
*/
const config = require('./config');
const restify = require('restify');
const restifyPlugins = require('restify-plugins');
/**
* Initialize Server
*/
const server = restify.createServer({
name: config.name,
version: config.version,
});
/**
* Middleware
*/
server.use(restifyPlugins.jsonBodyParser({ mapParams: true }));
server.use(restifyPlugins.acceptParser(server.acceptable));
server.use(restifyPlugins.queryParser({ mapParams: true }));
server.use(restifyPlugins.fullResponse());
/**
* Start Server, Connect to DB & Require Routes
*/
server.listen(config.port, (ctx,res) => {
// require('./routes')(server);
console.log(`Server is listening on port ${config.port}`);
});
复制代码
3.开启路由,routes文件中创建index.js,同时开启上方的注释。
/**
* Module Dependencies
*/
const errors = require('restify-errors');
module.exports = function(server) {
/**
* POST
*/
server.post('/todos', (req, res, next) => {
if (!req.is('application/json')) {
return next(
new errors.InvalidContentError("Expects 'application/json'"),
);
}
let data = req.body || {};
res.send("todos post ");
next();
});
/**
* LIST
*/
server.get('/todos', (req, res, next) => {
res.send("gete todos....");
next();
});
/**
* GET
*/
server.get('/todos/:todo_id', (req, res, next) => {
});
/**
* UPDATE
*/
server.put('/todos/:todo_id', (req, res, next) => {
});
/**
* DELETE
*/
server.del('/todos/:todo_id', (req, res, next) => {
});
};
复制代码
4.成功搭建rest api