Express Web Server Routing
suggest changeCreating 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.
- Go to the project directory and create a
package.jsonfile.
{
"name": "expressRouter",
"version": "0.0.1",
"scripts": {
"start": "node server.js"
},
"dependencies": {
"express": "^4.12.3"
}
}
-
Save the file and install the dependency with
npm install. This createsnode_modulesin the project directory. -
Create
server.jsin 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");
});
- Run the server:
node server.js
If the server starts, the console prints Live at Port 3000.
- 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: