node服务器响应静态资源

刚接触nodejs,写博客只是记录一下自己的学习心得
我这里的静态资源是指一个包括文字、图片、以及点击会有详情框的页面。需要2个js文件和一个html文件

  • 首先新建一个01.js文件
const http = require('http');
var server = http.createServer();
const fs = require('fs');
server.on('request', function (res, rso) {
      var urls = res.url;
    if (urls == '/') {
        rso.setHeader('Content-Type', 'text/html ;charset=utf-8');//设置编码 防止乱码
        fs.readFile('./index.html', 'utf8', function (err, data) {
            rso.end(data);
        })
    } else {
        fs.readFile('.'+urls,(err,data)=>{ //因为图片是在当前目录下,而服务其返回的是/img/1.jpg,所以要添加一个“.”
            rso.end(data);
        })
       
    }
});
server.listen(8081, function () {
    console.log('Server running at http://127.0.0.1:8081/');
});
  • 再建一个index.html,(---------不会html语言,只是举例,大佬勿喷-------)
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div>
        <p>shdsjhdjsk</p>
        <p>shdsds</p>
        <img src="./img/1.jpg" alt="">
        <h2>cbxnzbczx</h2>
        <p>fghgfhgfgh</p>
        <i>nm,cnbv,n</i>
        <s>u有风度与辐射</s>
    </div>
</body>
<script src='./img/index.js'></script>//点击效果
</html>
  • 再建一个index.js对应点击详情框效果
document.getElementsByTagName('img')[0].onclick=function () {
    alert('好看');//括号中的img为对应上面index.html的标签,选择img,代表点击图片才有详情框,选择‘p’就要点击第一段文字
    
}

最终效果:

原文地址:https://www.cnblogs.com/liu-ai-yu/p/13126474.html