Installing the Express framework
NPM Install-g Express
Send data using the Send method in Express
var express = require (' Express ');
var http = require (' http ');
Instantiate an object
var app = Express ();
App.get ('/index.html ', function (req,res) {
res.writehead (200,{' content-type ': ' text/html '});
Res.write ('
Use Express to set up routes
//set route var express = require (' Express '); var http = require (' http '); var app = Express (); App.get (
'/index.html/:id/:name ', function (req,res) {var str = ';
For (key in Req.params) {if (str!== ') {str = ' <br/> ';
str + = ' parameter name: ' + key;
STR + + String.fromCharCode (9) + ' parameter value: ' + Req.params[key];
} res.send (str); }) App.listen (1337, ' 127.0.0.1 ', function () {Console.log (' server is Listening ');})//test, browser open Localhost:1337/index.html/1/kong//
Output: Parameter name: ID parameter value: 1 Parameter name: Name parameter value: Kong//Use regular expression to set route var Express = require (' Express ');
var http = require (' http ');
var app = Express ();
Parameter plus the symbol, the blank app.get ('/index.html/:id?/:name? ', function (req,res) {var str = ') is displayed when no parameters are passed.
if (req.params.id) {str = = ' id parameter value: ' + req.params.id;
} if (req.params.name) {str = ' name parameter value: ' + req.params.name;
} res.send (str); }) App.listen (1337, ' 127.0.0.1 ', function () {Console.log (' server is Listening ');})//Another,/index.html/:id (*)/:name indicates that ID must begin with a,/ Index.html/:id (\\d+)/:name indicates that the ID must be a numeric
Use the next method to call the next get method that uses the same route
Use the next method to call the next get method that uses the same route
var express = require (' Express ');
var http = require (' http ');
var app = Express ();
App.get ('/index.html/:id/:name ', function (req,res,next) {
if (Req.params.id >) {
next ();
} else{
res.send (' ID parameter must be greater than ten ');
}
)
App.get ('/index.html/:id/:name ', function (req,res,next) {
res.send (' hello ');
})
App.listen (1337, ' 127.0.0.1 ', function () {
console.log (' Server listening ');
})