Nodejs rest api开发

本文利用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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值