Nodejs builds a web server

Create a web server using Nodejs + http 1, first create a server.js file, create a server, and the corresponding css and js file introduction and judgment Var http=require(‘http’); Var fs = require(‘fs’); Var url = require(‘url’);

//Create a server
http.createServer(function(request,response) {
/ / Resolve the request, including the file name
Var pathname= url.parse(request.url).pathname;
/ / Output the requested file name
Console.log("Request for "+ pathname + " received.");
/ / Get the suffix, judge whether it is js or css file, if the directory structure is different, you need to modify here
Var firstDir = pathname && pathname.split('/')[1];
Var ContentType = {'Content-Type': 'text/html'};

// js - application/x-javascript
If (firstDir && firstDir === 'static') {
ContentType = {'Content-Type': 'text/css'};
If (firstDir && firstDir === 'js') {
ContentType = {'Content-Type': 'application/x-javascript'}

/ / From the file system to request the contents of the file
fs.readFile(pathname.substr(1), function(err, data) {
If(err) {
//HTTP status code 404 : NOT FOUND
//Content Type: text/plain
response.writeHead(404, {'Content-Type': 'text/html'});
Else {
//HTTP status code 200 : OK
//Content Type: text/plain
response.writeHead(200, ContentType);

/ / Write back to the corresponding content
/ / Send response data

Console.log('Server running at');

2, create a simple html page, here are two borders, then a table, and in the second Add a previous click event to the border. As the introduction of another js file

index <!--

3, css style file and the content of the style tag written above Body { Border: 1px solid blue; }

	div {
	    border-radius: 10px;
	    width: 400px;
	    height: 200px;
	    border: 2px solid yellow;

4, this is a js file Console.log(’-successfully introduced js file-’); Function onClickDiv () { Alert (‘second click event’); }

The whole is so much! Detailed comments, you can look at it yourself, relatively simple, the specific steps I simply said:

1, download and install nodejs, the official website can be, here is http, there are The example uses express (need to be downloaded in nodejs, Detailed one can look at Baidu) 2, enter the js file that layer directory of this project, execute node server.js (here named server, specifically look at their own name) 3, the execution will print the server startup, and display the ip and port number 4, open the browser to view the effect

last picture:在这里插入图片描述