node如何实现根据不同url请求不同的html内容

本文主要针对实现node中根据不同url请求不同的html内容的方法。
核心实现步骤
获取请求的 url 地址
设置默认的响应内容 404 not found
判断用户请求是否为 / 或 /index.html 首页
判断用户请求的是 about.html 关于页面
设置 Content-Type 响应头,防止出现乱码
使用res.end() 把内容响应给客户端
代码实例
const http = require('http') const serve = http.createServer() serve.on('request',(req,res)=>{ // req 客户端请求的url地址 const url = req.url // 设置404返回内容 let content = '<h1>404 not found </h1>' if(url=='/' || url === '/index.html'){ content = '<h1>首页</h1>' }else if(url === '/about.html'){ content = '<h1>关于页面</h1>' } res.setHeader('Content-type','text/html;charset=utf-8') res.end(content) }) serve.listen(80,()=>{ console.log('serve running') })
小礼物走一波,支持作者
赏
还没有人赞赏,支持一波吧