位置:首页 > 后端 > node

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

dearweb 发布:2021-11-07 20:44:52阅读:

本文主要针对实现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')
})


24人点赞 返回栏目 提问 分享一波

小礼物走一波,支持作者

还没有人赞赏,支持一波吧

留言(问题紧急可添加微信 xxl18963067593) 评论仅代表网友个人 留言列表

暂无留言,快来抢沙发吧!

本刊热文
网友在读
手机扫码查看 手机扫码查看