Skip to content

Instantly share code, notes, and snippets.

@chengmu
Last active December 31, 2015 19:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chengmu/8035846 to your computer and use it in GitHub Desktop.
Save chengmu/8035846 to your computer and use it in GitHub Desktop.
Node Restful API Basic Example.md

Node Js in Action这本书的时候看到的一个用node http模块写的一个非常基础Restful API实现;附上使用curl命令的测试

####实现代码如下

var http = require('http'); 
var url = require('url');
var items = [];
var server = http.createServer(function(req, res){
  switch (req.method) {
    
    // POST 增
    case 'POST':
      var item = '';
      req.setEncoding('utf8');
      req.on('data', function(chunk){
        item += chunk;
      });
      req.on('end', function(){
        items.push(item);
        res.end('OK\n');
      });
    break;
    
    // GET 查
    case 'GET':
    items.forEach(function(item, i){
      res.write(i + ') ' + item + '\n');
    });
    res.end();
    break;

    // 删除
    case 'DELETE':
      var path = url.parse(req.url).pathname;//pathname是需要的参数部分
      var i = parseInt(path.slice(1), 10);//获取id
      if (isNaN(i)) {//验证数据有效性,永远记得错误输入总是存在的
        res.statusCode = 400;
        res.end('Invalid item id');
      } else if (!items[i]) {
        res.statusCode = 404;
        res.end('Item not found');
      } else {
        items.splice(i, 1);
        res.end('OK\n');
      }
    break;
    
    
    //例子没有给出put,自己试着实现了一个
    case 'PUT':
        var putPath = url.parse(req.url).pathname;
        var id = parseInt(putPath.slice(1), 10);

        var putItem = '';
        req.setEncoding('utf8');
        req.on('data', function(chunk) {
            putItem += chunk;
        });

        req.on('end', function() {
            if (isNaN(id)) {
                res.statusCode = 400;
                res.end('Invalid Item id');
            } else if (!items[id]) {
                res.statusCode = 404;
                res.end('Item not found');
            } else {
                items[id] = putItem;
            }
            res.end('ok\n');
        });

        break;
    
  }
}).listen(1234);
    

####在命令行中对应的测试命令: #####POST curl命令带上-d参数就是发post请求;

    curl -d 'buy onion'  http://127.0.0.1:1234 
    curl -d 'wash  dished'  http://127.0.0.1:1234 
    curl -d 'write default task'  http://127.0.0.1:1234 
    curl -d 'pubish toolkit'  http://127.0.0.1:1234 

#####GET curl默认就是get.

    curl http://127.0.0.1:1234


----------


----------

终端显示:

$ curl  http://127.0.0.1:1234
0) buy onion
1) wash  dished
2) write default task
3) pubish toolkit

#####DELETE 需要带参数-X; 此外,要注意“DELETE”需要双引号。单引号会报错

    curl -X "DELETE" http://127.0.0.1:1234/1
    \\ 再运行get
    curl http://127.0.0.1:1234/

终端显示

    $ curl  http://127.0.0.1:1234
    0) buy onion
    1) write default task
    2) pubish toolkit

#####PUT -d 带上"数据" -X PUT 代表PUT方法

    curl -X PUT  -d "work out"  http://127.0.0.1:1234/0

####Misc 此外还学到了有趣的豆知识!

####What is REPL? "读取-求值-输出"循环 Read-Eval-Print Loop

一个简单的,交互式的编程环境。这个词常常用于指代一个Lisp的交互式开发环境,但也能指代命令行的模式和例如 APL, BASIC, Clojure, F#, Haskell, J, Julia, Perl, PHP, Prolog, Python, R, Ruby, Scala, Smalltalk, Standard ML, Tcl, Javascript 这样的编程语言所拥有的类似的编程环境。这也被称做__交互式顶层构件(interactive toplevel)__。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment