Friday, March 25, 2016

Node Js: Basic Express Route Notes

Routes are super easy in Express. Given the following js you can see a get for root and kittens, and a post for kitten.

var express  = require('express');
var app = express();
app.get('/',function(req,res){
    console.log('Got a get for /');
    res.send("You are getting root")
})

app.get('/kittens',function(req,res){
    console.log('Got a get for /kittens');
    res.send("You are getting kittens")
})

app.post('/kitten',function(req,res){
    console.log('posted a post for /kitten');
    res.send("You are posting kitten")
})

var server = app.listen(8081, function(){
    var host = server.address().address
    var port = server.address().port
    console.log("Example app listening at http://%s:%s", host, port)
})

Using a tool like Postman, if you issue a GET to http://127.0.0.1:8081/kitten you will see  an error
     Cannot GET /kitten
This is because a GET route defined on kittens, not kitten. This is the same as requesting an undefined route for http://127.0.0.1:8081/kittenzzzz. However doing a GET to http://127.0.0.1:8081/kittens returns our coded responce, same as a POST to http://127.0.0.1:8081/kitten
    You are getting kittens
 

No comments:

Post a Comment