美文网首页
使用HTTP模块搭建服务器

使用HTTP模块搭建服务器

作者: 圆滚滚大煤球 | 来源:发表于2021-11-17 17:38 被阅读0次

使用HTTP模块搭建服务器

// 导入http模块
const http = require('http')

// 创建web服务实例对象
const server = http.createServer()



// // 为server绑定request事件,监听客户端的请求
server.on('request',(req, res)=>{
// 获取url地址
const url = req.url;
// 设置默认内容为404 Not Found
let content = '404 Not Found!';
// 判断用户请求是否为 / 或者/index.html 首页

if(url === '/' || url === '/index.html'){
    content = '<h1>首页</h1>';
// 判断用户请求是否为about.html 关于页面
} else if(url === '/about.html'){
    content = '<h1>关于页面</h1>';
}

// 调用res.setHeader()方法,设置Content-type响应头,为了防止中文乱码
res.setHeader('Content-type','text/html; charset=utf-8')

// 使用res.end()把内容响应给客户端
res.end(content)
})


// 启动服务器
// 端口号如果是80则可以省略不写,其他的必须写
server.listen(80,()=>{
    console.log('Server running at http://127.0.0.1');
})

// 打开终端后 CTRL+鼠标左键点击http://127.0.0.1 即可打开网址

实现clock时钟的web服务器


// 1.1 导入 http 模块
const http = require('http')
// 1.2 导入 fs 模块
const fs = require('fs')
// 1.3 导入 path 模块
const path = require('path')

// 2.1 创建 web 服务器
const server = http.createServer()
// 2.2 监听 web 服务器的 request 事件
server.on('request', (req, res) => {
  // 3.1 获取到客户端请求的 URL 地址
  //     /clock/index.html
  //     /clock/index.css
  //     /clock/index.js
  const url = req.url
  // 3.2 把请求的 URL 地址映射为具体文件的存放路径
  // const fpath = path.join(__dirname, url)
  // 5.1 预定义一个空白的文件存放路径
  let fpath = ''
  if (url === '/') {
    fpath = path.join(__dirname, './clock/index.html')
  } else {
    //     /index.html
    //     /index.css
    //     /index.js
    fpath = path.join(__dirname, '/clock', url)
  }

  // 4.1 根据“映射”过来的文件路径读取文件的内容
  fs.readFile(fpath, 'utf8', (err, dataStr) => {
    // 4.2 读取失败,向客户端响应固定的“错误消息”
    if (err) return res.end('404 Not found.')
    // 4.3 读取成功,将读取成功的内容,响应给客户端
    res.end(dataStr)
  })
})
// 2.3 启动服务器
server.listen(80, () => {
  console.log('server running at http://127.0.0.1')
})

相关文章

  • 使用HTTP模块搭建服务器

    使用HTTP模块搭建服务器 实现clock时钟的web服务器

  • node.js-http模块深入理解

    http模块主要用于搭建HTTP服务端和客户端,使用HTTP服务器或客户端功能都必须调用http模块。 创建服务器...

  • Node.js(服务器与fs的搭建)

    服务器搭建:http模块 语法: 1.引入http服务器模块 2.通过这个模块创建服务器 createServer...

  • nodejs(4)

    重要的http模块 主要用于搭建http服务器和客户端 http中文名,超文本传输协议 常用的api创建服务器使用...

  • Node.js 之 http模块

    http模块 引入http模块 开启一个本地服务器需要Node.js中http核心模块http--模块提供了搭建本...

  • NodeJS-http模块

    搭建一个http的服务器,用户处理用户发送的http请求,需要使用node提供的一个模块:http; res.wr...

  • IT兄弟会全栈工程师精英班第四天(学习笔记)

    搭建静态资源服务器之node HTTP模块 1. 代码如下:const http = require('http...

  • nodeJS内置模块

    1、http模块 创建服务器 使用 http.createServer() 方法创建服务器,并使用 listen ...

  • node服务器搭建

    今天晚上学习了一下怎么搭建服务器,使用原生的http模块,在这里总结一下心得。首先我们介绍几个模块内容,(模块的方...

  • nodejs搭建服务器

    1.使用内置http搭建服务 2.基于express模块搭建服务

网友评论

      本文标题:使用HTTP模块搭建服务器

      本文链接:https://www.haomeiwen.com/subject/mxzltrtx.html