Routing refers to the definition of end points (URIs) to an application and how it responds to client requests.
A route is a combination of a URI, a HTTP request method (GET, POST, and so on), and one or more handlers for the endpoint. It takes the following structure app.METHOD(path, [callback...], callback)
, where app
is an instance of express
, METHOD
is an HTTP request method, path
is a path on the server, and callback
is the function executed when the route is matched.
The following is an example of a very basic route.
//install the module and adds to package.json
//$ npm install --save express
var express = require('express');
var app = express();
app.get('/', function (request, response) {
response.sendFile(__dirname + "/index.html");
});
app.listen(8080);
that accespts dynamic arguments in the url
var express = require('express');
var app = express();
var quotes = {
'einstein': 'Life is like riding a bicycle. To keep your balance you must keep moving',
'berners-lee': 'The Web does not just connect machines, it connects people',
'crockford': 'The good thing about reinventing the wheel is that you can get a round one',
'hofstadter': 'Which statement seems more true: (1) I have a brain. (2) I am a brain.'
};
app.get('/quotes/:name', function (request, response) {
var name = request.params.name;
response.send(quotes[name]);
response.end();
});
app.listen(8080);
Open your browser with address ex: http://localhost:8080/quote/einstein
example to call url like this : https://github.com/search?q=nodejs
var url = require('url');
var request = require('request');
var options = {
protocol: "https:",
host: "github.com",
pathname: '/search',
query: {
q: "nodejs"
}
};
var searchURL = url.format(options);
var express = require('express');
var app = express(); // Create server here
app.get('/', function(req,res){
request(searchURL).pipe(res);
});
app.listen(8080);