创建简单的web服务器
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| const http = require("http")
const server = http.createServer()
server.on("request",(req,res)=>{ console.log("Soneone visit our web server.") const url = req.url const method = req.method var str = `your url is ${url} , and method ${method}` res.end(str) })
server.listen(8080,function(){ console.log("server running at http://172.0.0.1:8080") })
|
易错点
在给客户端返回字符串的需要插入参数时,需要使用"`"反单引号,在Esc下面的键。
解决响应消息中文乱码问题
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| const http = require("http")
const server = http.createServer()
server.on("request",function(req,res){ res.setHeader("Content-Type","text/html; charset=utf-8") const url = req.url var str = `你请求的url为:${url}` res.end(str) })
server.listen(8080,function(){ console.log("服务器已启动 http://172.0.0.1:8080") })
|
配置路由
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| const http = require("http") const path = require("path") const fs = require("fs") const server = http.createServer()
server.on("request",(req,res)=>{ const url = req.url var fpath = path.join(__dirname,url) console.log(fpath) fs.readFile(fpath,"utf-8",function(err,data){ if (err){ return console.error(err) } res.end(data) }) })
server.listen(8080,function(){ console.log("服务器已启动 http://172.0.0.1:8080") })
|