Node.js使用原生创建服务及实现静态资源托管/接口请求
1.环境
采用12.13.x版本
2.创建server.js
文件内容如下:
1 let http = require("http"); 2 let fs = require("fs"); 3 4 let server = http.createServer((req, res) => { 5 if (req.url.indexOf("/api") !== -1) { 6 console.log("这是接口地址") 7 } else { 8 let path = req.url === "/" ? "/index.html" : req.url; 9 try { 10 let data = fs.readFileSync("./www" + path); 11 res.write(data); 12 res.end(); 13 } catch (e) { 14 let error = fs.readFileSync("./www/error.html"); 15 res.write(error); 16 res.end(); 17 } 18 } 19 }); 20 server.listen(80, () => { 21 console.log("server is running") 22 })