// introducing the HTTP module var http = require (' http '); // Call HTTP Createserver method, this method has a callback function, this callback number // the function is to execute this callback function http.createserver (function (req, res) { //) until the request is sent to the server. Send res.end (' Hello world\n ');}). Listen (3000, "127.0.0.1"); // port and IP bindings console.log (' Server running at Http://127.0.0.1:3000/');
The above code, create a server, and set the content sent to the client, the following talk about the redirection in node. js
var http = require (' http '); Http.createserver (function (req, res) { // redirect , Writehead method res.writehead (301, { ' location ': ' Http://www.baidu.com ' }); Res.end ();}). Listen ("127.0.0.1"); Console.log (' Server running at Http://127.0.0.1:3000/');
By setting up a route to respond to different requests ( essentially ), this is actually getting more complicated, because if there are many kinds of responses, If--else will be more and more, and the express framework will be introduced later.
varHTTP = require (' http '), URL= require (' URL '); Http.createserver (function(req, res) {//parse URL, get path name varpathname =Url.parse (req.url). Pathname; if(Pathname = = = '/')) {Res.writehead (200, { ' Content-type ': ' Text/plain ' }); Res.end (' Home page\n ') } Else if(Pathname = = = '/about ')) {Res.writehead (200, { ' Content-type ': ' Text/plain ' }); Res.end (' About us\n ') } Else if(Pathname = = = '/redirect ')) {Res.writehead (301, { ' Location ': '/' }); Res.end (); } Else{Res.writehead (404, { ' Content-type ': ' Text/plain ' }); Res.end (' Page not found\n ')}). Listen (3000, "127.0.0.1"); Console.log (' Server running at Http://127.0.0.1:3000/');
Create a client with node. js
var http = require (' http ' , Port: 80 '/' };http.get (Options , function (res) { if (Res.statuscode = = 200 "The site is up!" ); else {Console.log ( "The site is down! " ); }}). On ( ' error ', function (E) { Console.log ( There is an error: "+ e.message);});
node. JS Learning Notes under Windows (5)---Creating Servers and clients with node. js