The content of this article is about the implementation code of router control in Node.js. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
render.js:
//引入模块 let http = require("http"); let fs = require("fs"); //创建HTTP服务 http.createServer(function (req,res) { if (req.url === "/favicon.ico"){ return false; } if (req.url === "/" || req.url === "/index.html"){ // 读取文件 fs.readFile("./index.html",function (err,data) { //设置响应头 res.writeHead(200,{ "Content-type":"text/html;charset=utf-8" }); //结束响应 res.end(data); }) }else if(req.url === "/show.html"){ // 读取文件 fs.readFile("./show.html",function (err,data) { //设置响应头 res.writeHead(200,{ "Content-type":"text/html;charset=utf-8" }); //结束响应 res.end(data); }) }else if(req.url === "/image/1.jpg" ){ //读取文件 fs.readFile("./image/1.jpg",function (err,data) { //设置响应头 res.writeHead(200,{ "Content-type":"image/jpeg" }); //结束响应 res.end(data); }) }else if(req.url === "/style.css"){ //读取文件 fs.readFile("./style.css",function (err,data) { //设置响应头 res.writeHead(200,{ "Content-type":"text/css" }); // 结束响应 res.end(data); }) } else { res.writeHead(404,{ "Content-type":"text/html;charset=utf-8" }); res.end("您访问的也没不存在"); } console.log(req.url); }).listen(3200,function () { console.log("Http Server running on port 3200"); })
index.html:
<h1>你好</h1> <img src="/image/1.jpg" alt="">
show.html:
<h1>你好,全世界</h1>
style.css:
h1 { font-size: 18px; } img{ width: 50%; }
Related recommendations :
Usage of Nodejs routing and controller
The above is the detailed content of Implementation code of router control in Node.js. For more information, please follow other related articles on the PHP Chinese website!