NodeJs WebApi

RESTful API

GET  /products

var express = require('express')
var app = express();

var products = [
   { name: 'apple juice', description: 'good', price: 12.12 },
   { name: 'banana juice', description: 'just so sos', price: 4.50 }
]

app.get('/products', function(req, res) {
   res.json(products);
});

var server = app.listen(3000, function() {
   console.log('listening on port %d', server.address().port);
})



GET /products/:id => 200

app.get('/products/:id', function(req, res) {
   res.json(products[req.params.id]);
})



GET /products/:id => 404

app.get('/products/:id', function(req, res) {
   if (products.length <= req.params.id || req.params.id < 0) {
      res.statusCode = 404;
      return res.send('Error 404: No products found')
   }
   res.json(products[req.params.id]);
})



POST /products => 201

因为我们在接受POST请求的时候,需要解析POST的body,所以,我们就要使用middleware来做这件事情,在早期版本中提供了bodyParser这样的方式。但是这种方式会创建大量的临时文件。所以,我们应该直接使用json或者urlencoded这样的middleware直接解析

在package.json中添加依赖:

    "body-parser": "1.4.3"



var express = require('express'),
   bodyParser = require('body-parser')

var app = express()
   .use(bodyParser.json());

app.post('/products', function(req, res) {
   var newProduct = {
      name: req.param('name'),
      description: req.param('description'),
      price: req.param('price')
   }

   products.push(newProduct);
   res.statusCode = 201;
   res.location('/products/' + products.length);
   res.json(true);
});



POST /products => 400

app.post('/products', function(req, res) {
   if (typeof req.param('name') === "undefined" ||
      typeof req.param('description') === "undefined" ||
      typeof req.param('price') === "undefined") {
      res.statusCode = 400;
      res.send('Error 400: products properties missing');
   }
   //......
});

你可能感兴趣的:(NodeJs WebApi)