nodejs creates a server and refreshes the page content according to different URLs (absolute path)

 Refresh different pages based on different URLs

/*
服务器
//1.引入http模块
//2.创建server对象
//3.绑定端口和ip
//4.监听浏览器请求服务事件
//5.响应数据给浏览器
*/
const fs = require("fs");
// 使用http 模块 封装好的服务器的API
const http = require("http");
// 创建一个服务器
const server = http.createServer();
// 创建相应的端口 绑定ip  127.0.0.1 本地ip (localhost) 只能自己访问 所有本地都是这个
// 8080端口号是可以修改 建议用8000以上的(自定义端口号)  //自己电脑的IP地址局域网别人可以访问
server.listen("8080"); //不写就是默认本地ip地址
server.on("request", (request, response) => {
    // 有css就不能在这里放  text/html; 在里面放 html和css分开使用
    // response.setHeader("Content-Type", "text/html;charset=utf-8")
    console.log("请求路径" + request.url);
    var url = request.url
    // 页面里面有css img js 必须一起请求 不然会出不来效果
    if (url === "/index.html") {
        fs.readFile("./index/index.html", (err, data) => {
            response.end(data)
        })
        // html静态文件
    } else if (url === "/list.html") {
        fs.readFile("./index/list.html", (err, data) => {
            response.end(data)
        })
        // css静态文件
    } else if (url === "/css/index.css") {
        response.setHeader("Content-Type", "text/css;charset=utf-8")
        // css 使用 text/css;
        fs.readFile("./css/index.css", (err, data) => {
            response.end(data)
        })
        // 图片静态文件
    } else if (url === "/img/1.webp") {
        fs.readFile("./img/1.webp", (err, data) => {
            response.end(data)
        })
        // js静态文件
    } else if (url === "/js/index.js") {
        fs.readFile("./js/index.js", (err, data) => {
            response.end(data)
        })
    }
})

 There are css img js in the page, they must be requested together, otherwise the effect will not come out, so you need to import all the links

You can judge the path format based on this

Simplify the link path 

A path format adapts to multiple links by obtaining the current URL as the path

Determine the parent folder (starting path) for classification processing

const fs = require("fs")
const http = require("http")
const server = http.createServer()
server.listen("8080")
server.on("request", (req, res) => {
    console.log("有请求" + req.url);
    if (/^\/css/.test(req.url) || /^\/img/.test(req.url) || /^\/js/.test(req.url)) {
        // 给css做防止中文乱码 data是数据不会乱码 只有直接加文字才会
        res.setHeader("Content-Type", "text/css;charset=utf-8");
        fs.readFile("." + req.url, (err, data) => {
            res.end(data)
        })
    } else if (/^\/index/.test(req.url)) {
        // 给html做防止中文乱码 data是数据不会乱码 只有直接加文字才会
        res.setHeader("Content-Type", "text/html;charset=utf-8");
        fs.readFile("./index" + req.url, (err, data) => {
            res.end(data)
        })
    }
})

Absolute path (static resource)  

__dirname is a dynamic absolute path

Function: prevent the path from being changed due to changing the file location

// 绝对路径__dirname 可以访问所有路径  所以要加限制条件以固定开头的才可以访问
  // __dirname 是根据当前的文件夹的路径 所以启动服务器的js文件要和其他文件夹在同一个目录(不用在给这个单独加一个父级文件夹)
  //  __dirname拿到的绝对路径是相当于大文件 所以要把静态资源文件放在一个文件夹里面 方便统一处理
  if (
    /^\/css/.test(req.url) ||
    /^\/img/.test(req.url) ||
    /^\/js/.test(req.url)
  ) {
    // 给css做防止中文乱码 data是数据不会乱码 只有直接加文字才会
    // res.setHeader("Content-Type", "text/css;charset=utf-8");
    console.log("绝对路径" + __dirname+req.url);
    // __dirname 当前文件  "E:\笔记2\nodejs\day1\作业/index/index.html"
    fs.readFile(__dirname + req.url, (err, data) => {
      res.end(data);
    });
  } else if (/^\/index/.test(req.url)) {
    fs.readFile(__dirname + "/index" + req.url, (err, data) => {
      res.end(data);
    });
  }

Because index.js is a relatively large folder where the server file is an absolute path

The obtained path lacks a parent, so the index.js file needs to add a separate /index

To solve this problem, you can put all files in the same folder ( but it is confusing and not recommended )

 An if judges whether it is accessible and can be processed in a unified manner. All files at the same level are added with " . "

// 路径
const fs = require("fs");
// 服务器
const http = require("http");
const server = http.createServer();
server.listen(9090);
server.on("request", (req, res) => {
//   res.end("<h1>hello world!</h1>");
  if (
    /^\/css/.test(req.url) ||
    /^\/img/.test(req.url) ||
    /^\/js/.test(req.url) ||
    /^\/index/.test(req.url)
  ) {
    // __dirname  "E:\笔记2\nodejs\day1\静态资源绝对路径/";
    console.log("绝对路径" + __dirname + req.url);
    fs.readFile(__dirname + req.url, (err, data) => {
      res.end(data);
    });
    //   console.log("相对路径" + req.url);
    //   fs.readFile("." + req.url, (err, data) => {
    //       res.end(data);
    //   });
  }
});

Guess you like

Origin blog.csdn.net/weixin_70563937/article/details/126202953