当前位置:   article > 正文

Nodejs rest api开发

const server = restify.createserver({

本文利用nodejs+restify 开发rest api,非express 等rest服务。去除了多余的模板内容。

操作步骤:

1.下载依赖:

  1. cnpm install restify restify-plugins restify-errors --save
  2. 复制代码

2.hello-world:

  1. /**
  2. * Module Dependencies
  3. */
  4. const config = require('./config');
  5. const restify = require('restify');
  6. const restifyPlugins = require('restify-plugins');
  7. /**
  8. * Initialize Server
  9. */
  10. const server = restify.createServer({
  11. name: config.name,
  12. version: config.version,
  13. });
  14. /**
  15. * Middleware
  16. */
  17. server.use(restifyPlugins.jsonBodyParser({ mapParams: true }));
  18. server.use(restifyPlugins.acceptParser(server.acceptable));
  19. server.use(restifyPlugins.queryParser({ mapParams: true }));
  20. server.use(restifyPlugins.fullResponse());
  21. /**
  22. * Start Server, Connect to DB & Require Routes
  23. */
  24. server.listen(config.port, (ctx,res) => {
  25. // require('./routes')(server);
  26. console.log(`Server is listening on port ${config.port}`);
  27. });
  28. 复制代码

3.开启路由,routes文件中创建index.js,同时开启上方的注释。

  1. /**
  2. * Module Dependencies
  3. */
  4. const errors = require('restify-errors');
  5. module.exports = function(server) {
  6. /**
  7. * POST
  8. */
  9. server.post('/todos', (req, res, next) => {
  10. if (!req.is('application/json')) {
  11. return next(
  12. new errors.InvalidContentError("Expects 'application/json'"),
  13. );
  14. }
  15. let data = req.body || {};
  16. res.send("todos post ");
  17. next();
  18. });
  19. /**
  20. * LIST
  21. */
  22. server.get('/todos', (req, res, next) => {
  23. res.send("gete todos....");
  24. next();
  25. });
  26. /**
  27. * GET
  28. */
  29. server.get('/todos/:todo_id', (req, res, next) => {
  30. });
  31. /**
  32. * UPDATE
  33. */
  34. server.put('/todos/:todo_id', (req, res, next) => {
  35. });
  36. /**
  37. * DELETE
  38. */
  39. server.del('/todos/:todo_id', (req, res, next) => {
  40. });
  41. };
  42. 复制代码

4.成功搭建rest api

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家自动化/article/detail/723422
推荐阅读
相关标签
  

闽ICP备14008679号