【node】 8、http搭建服务器模块(创建自己的第二个网站)

创建自己的第一个网站:
11.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>我的网站</title>
</head>
<body>
    <h2>我的网站首页</h2>
    <a href="./wdjl">我的简历<a>
    <h3>我的作品</h3>
    <h3>我的学习</h3>
    <h3>我的家乡</h3>
    <h3>我的就业</h3>
    <img src="/img" alt="">
</body>
</html>

22.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>我的简历</title>
</head>
<body>
    <a href="./index">返回我的网站首页</a>
    <h3>这是我的简历详情<h3>
    <p>我是海绵宝宝,我有一个朋友叫派大星还有一个叫章鱼哥,我的老板是谢老板<p>
</body>
</html>

http.js

const http = require('http');  //http模块搭建服务
const fs = require('fs')       //fs模块读取文件数据
const url = require('url');    //url模块专门用来处理地址栏的信息

var server = http.createServer(function (req, res) {
  //pathname: 获取localhost:3000/后面的路径
  const { pathname, query } = url.parse(req.url)
  console.log(pathname);
  if (pathname == '/index') {
    fs.readFile('./11.html', function (err, data) {
      if (err) return
      res.end(data)
    })
  } else if (pathname == '/wdjl') {
    fs.readFile('./22.html', function (err, data) {
      if (err) return
      res.end(data)
    })
  } else if (pathname === '/img') {  //请求图片资源
    fs.readFile('./2.jpg', function (err, data) {
      if (err) return
      res.end(data)
    })
  }else {
    res.setHeader('content-type', 'text/html;charset=utf-8')
    res.end('404页面')
  }

})
server.listen(3000, function () {
  console.log('3000端口成功运行')
})

终端开启服务
在这里插入图片描述
浏览器访问:
在这里插入图片描述

发布了218 篇原创文章 · 获赞 35 · 访问量 13万+

猜你喜欢

转载自blog.csdn.net/qq_41614928/article/details/102532139