Express Web Server Routing

suggest change

Creating Express Web Server

Express is a widely used web framework. Let's create a small server. We will use npm (Node Package Manager) for dependencies.

  1. Go to the project directory and create a package.json file.
{
  "name": "expressRouter",
  "version": "0.0.1",
  "scripts": {
    "start": "node server.js"
  },
  "dependencies": {
    "express": "^4.12.3"
  }
}
  1. Save the file and install the dependency with npm install. This creates node_modules in the project directory.

  2. Create server.js in the project directory.

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

//Creating Router() object
var router = express.Router();

// Provide all routes here, this is for Home page.
router.get("/", function(req, res) {
  res.json({"message" : "Hello World"});
});

app.use("/api", router);

// Listen to this Port
app.listen(3000, function() {
  console.log("Live at Port 3000");
});
  1. Run the server:
node server.js

If the server starts, the console prints Live at Port 3000.

  1. In a browser or Postman, request:
http://localhost:3000/api/

The response body is {"message":"Hello World"}.

That is the basic Express routing example.

Now let's log the method of each request. Change server.js to:

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

//Creating Router() object

var router = express.Router();

// Router middleware, mentioned it before defining routes.

router.use(function(req,res,next) {
  console.log("/" + req.method);
  next();
});

// Provide all routes here, this is for Home page.

router.get("/",function(req,res){
  res.json({"message" : "Hello World"});
});


app.use("/api",router);


app.listen(3000,function(){
  console.log("Live at Port 3000");
});

Restart the server and request:

http://localhost:3000/api/

The console prints the method, and the response looks like this:

Accessing Parameter in Routing

Route parameters come from the URL, for example http://example.com/api/user/:id. req.params.id is that value. Add this route to server.js:

router.get("/user/:id",function(req,res){
  res.json({"message" : "Hello "+req.params.id});
});

Restart the server and open http://localhost:3000/api/user/Adem. The response looks like this:

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents