When we open the browser browse the web, click on different modules above, routing the address bar will change accordingly, and thus, the browser initiates a request to a server content may also change, then the server, how to do it ?
The server is to respond differently through the route, we already know that the server object parameters are request, response, and the two parameters. request was to carry a browser request value carried.
request.url returns the value of the browser route
We can be judged according to this value, the server needs to return what the browser,
Server.js look at the following code:
var http = require("http"); var fs = require("fs"); var startServer = function(){ var onRequest = function(request,response){ console.log("request received"+request.url); if(request.url==="/"||request.url==="/home"){ response.writeHead(200,{"Content-Type":"text/html"}); fs.createReadStream(__dirname+"/index.html","utf8").pipe(response); }else if(request.url==="/review"){ response.writeHead(200,{"Content-Type":"text/html"}); fs.createReadStream(__dirname+"/review.html","utf8").pipe(response); }else if(request.url==="/api"){ response.writeHead(200,{"Content-Type":"application/json"}); var jsonObj={name:"lili",job:"coder",age:18}; response.end(JSON.stringify(jsonObj)); }else{ response.writeHead(200,{"Content-Type":"text/html"}); fs.createReadStream(__dirname+"/404.html "," utf8 " ) .pipe (the Response); } } var Server = http.createServer (onRequest); // let the server listens on a port server.listen (3000," 127.0.0.1 "); // the second parameter may further add 127.0.0.1 is a local representative of the console.log ( "started ON localhost server Port 3000"); // add a server starts up tips } module.exports.startServer = the startServer;
Server.js the above, depending on the route, so the server returns to a different browser content when content can not be found, a 404 page
The server.js into the app.js
var server = require("./server"); server.startServer();
Execution node app
In the browser localhost: 3000
Later followed by various routes, will show different pages when no route is matched, it displayed 404 pages! ! !