This chapter to learn how to send in NodeJs in Html files to the client, as well as the definition of Content-Type Content Type
// 1, http and fs loading module var http = the require ( "http" ); var fs = the require ( 'fs' ); // 2, create an http service var Server = http.createServer (); // . 3 set a Http listening port, the browser requests 127.0.0.1:8000 triggered request server.listen (8080, function () { console.log ( "service started successfully" ) }) // 4, listens request request event, setting request, response callback server.on ( "Request", function (request, response) { IF (== request.url "/" ) { fs.readFile ( 'index.html', function (error, Data) { IF (error) { // when a read failure when response.setHeader ( 'the Content-the Type', 'text / Plain; charset = UTF-. 8' ) Response.End ( "file read failed" ); } the else { // successfully read the web page returned to the client response.setHeader ( 'the Content-the Type', 'text / HTML; charset = UTF-. 8' ) Response.End (Data); } }) } })
Index.html file contents
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <link href="css.css"> </head> <body> <h1>首页</h1> </body> </html>