Getting started with Node.jsnpmWeb Apps With ExpressFilesystem I/OExporting and Consuming ModulesExporting and Importing Module in node.jsInstalling Node.jsMySQL integrationReadlinepackage.jsonEvent EmittersAutoreload on changesEnvironmentCallback to PromiseExecuting files or commands with Child ProcessesCluster ModuleException handlingKeep a node application constantly runningUninstalling Node.jsnvm - Node Version ManagerhttpUsing StreamsDeploying Node.js applications in productionSecuring Node.js applicationsMongoose Libraryasync.jsFile uploadSocket.io communicationMongodb integrationHandling POST request in Node.jsSimple REST based CRUD APITemplate frameworksNode.js Architecture & Inner WorkingsDebugging Node.js applicationNode server without frameworkNode.JS with ES6Interacting with ConsoleCassandra IntegrationCreating API's with Node.jsGraceful ShutdownUsing IISNode to host Node.js Web Apps in IISCLINodeJS FrameworksgruntUsing WebSocket's with Node.JSmetalsmithParsing command line argumentsClient-server communicationNode.js Design FundamentalConnect to MongodbPerformance challengesSend Web NotificationRemote Debugging in Node.JSMysql Connection PoolDatabase (MongoDB with Mongoose)Good coding styleRestful API Design: Best PracticesDeliver HTML or any other sort of fileTCP SocketsHackBluebird PromisesAsync/AwaitKoa Framework v2Unit testing frameworksECMAScript 2015 (ES6) with Node.jsRouting ajax requests with Express.JSSending a file stream to clientNodeJS with RedisUsing Browserfiy to resolve 'required' error with browsersNode.JS and MongoDB.Passport integrationDependency InjectionNodeJS Beginner GuideUse Cases of Node.jsSequelize.jsPostgreSQL integrationHow modules are loadedNode.js with OracleSynchronous vs Asynchronous programming in nodejsNode.js Error ManagementNode.js v6 New Features and ImprovementEventloopNodejs Historypassport.jsAsynchronous programmingNode.js code for STDIN and STDOUT without using any libraryMongoDB Integration for Node.js/Express.jsLodashcsv parser in node jsLoopback - REST Based connectorRunning node.js as a serviceNode.js with CORSGetting started with Nodes profilingNode.js PerformanceYarn Package ManagerOAuth 2.0Node JS LocalizationDeploying Node.js application without downtime.Node.js (express.js) with angular.js Sample codeNodeJs RoutingCreating a Node.js Library that Supports Both Promises and Error-First CallbacksMSSQL IntergrationProject StructureAvoid callback hellArduino communication with nodeJsN-APIMultithreadingWindows authentication under node.jsRequire()Route-Controller-Service structure for ExpressJSPush notifications

NodeJs Routing

Other topics

Remarks:

At last, Using Express Router you can use routing facility in you application and it is easy to implement.

Express Web Server Routing

Creating Express Web Server

Express server came handy and it deeps through many user and community. It is getting popular.

Lets create a Express Server. For Package Management and Flexibility for Dependency We will use NPM(Node Package Manager).

  1. Go to the Project directory and create package.json file. package.json { "name": "expressRouter", "version": "0.0.1", "scripts": { "start": "node Server.js" }, "dependencies": { "express": "^4.12.3" } }

  2. Save the file and install the express dependency using following command npm install. This will create node_modules in you project directory along with required dependency.

  3. Let's create Express Web Server. Go to the Project directory and create server.js file. server.js

    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"); });

For more detail on setting node server you can see [here][1].
  1. Run the server by typing following command.

    node server.js

    If Server runs successfully, you will se something like this.this.

  2. Now go to the browser or postman and made a request

    http://localhost:3000/api/

    The output will be this.

That is all, the basic of Express routing.

Now let's handle the GET,POST etc.

Change yous server.js file like

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");
});

Now if you restart the server and made the request to

http://localhost:3000/api/

You Will see something like this

Accessing Parameter in Routing

You can access the parameter from url also, Like http://example.com/api/:name/. So name parameter can be access. Add the following code into your server.js

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

Now restart server and go to [http://localhost:3000/api/user/Adem][4], the output will be like this.

Contributors

Topic Id: 9846

Example Ids: 30304

This site is not affiliated with any of the contributors.