node基础-使用node的内置模块

1.node的内置模块 - http

http模块-----服务器模块(后端)
功能:
	搭建服务器 完成服务器功能
	发起请求(类似ajax)  --- 不会产生跨域
	node中全面支持es6
	
const http = require("http");
// console.log(http);
// 创建一个服务器,返回一个服务对象
const serverObj = http.createServer((req, res)=>{
    // 所有的服务器逻辑
    // req:request请求对象:从前端到后端
    // res:response响应对象:从后端到前端

    // 暂时过滤favicon图标
    if(req.url !== "/favicon.ico"){
        console.log("有人访问了这个服务器")
        
        // 设置发送给前端的数据格式为utf-8,仅在测试时使用
        res.writeHead(200,{"content-type":"text/html;charset=utf-8"})

        // 路由处理:根据前端过来的地址,执行指定的功能
        switch(req.url){
            case "/":
                res.write("首页");break;
            case "/index":
                res.write("首页");break;
            case "/page":
                res.write("分页");break;
            case "/news":
                res.write("新闻");break;
            default:
                res.write("404");
        }
        // 断开本次请求
        res.end();
    }
});

// 在服务对象身上监听:地址和端口,设定监听成功后的回调函数
// 端口必传 其他参数可以省略
serverObj.listen("3000","127.0.0.1",()=>{
    console.log("服务器开启成功,请访问:http://127.0.0.1:3000")
});

2.node的内置模块 - fs

const fs = require("fs");
// console.log(fs);


// 文件的读和写


// 写 - 异步:
// 参数1:要写入的文件的地址
//     存在此文件,直接写入
//     不存在此文件,先创建,再写入
// 参数2:
//     要写入文件的内容
// 参数3:
//     写入成功后执行的回调函数
// fs.writeFile("./hello.txt", "你好这是node创建的记事本", ()=>{
//     console.log("文件写入成功")
// })

// 写 - 同步:
// fs.writeFileSync("./world.txt", "这是文件使用node同步方法写入的内容")
// console.log("文件写入成功");



// 读 - 异步
// 参数1:要读取的文件的地址
// 参数2:读取文件后的数据的解析格式
// 参数3:读取成功后的回调函数
//     参数1:错误对象
//     参数2:读取成功后的文件数据
// fs.readFile("./world.txt","utf-8",(err, data)=>{
//     console.log(err);
//     if(!err){
//         console.log(data);
//     }
// })

// 读 - 同步
const data = fs.readFileSync("./world.txt","utf-8");
console.log(data);

3.http模块和fs模块结合

const http = require("http");
const fs = require("fs");

http.createServer((req, res)=>{
    if(req.url !== "/favicon.ico"){
    	// 假设路径
        // "/" === "./www/"
        // "/index.html" === "./www/index.html"
        // "/page.html" === "./www/page.html"

        fs.readFile("./www" + req.url, (err, data)=>{
            if(!err){
                res.write(data);
            }else{
                res.write("404");
            }
            // 注意异步的坑
            res.end();
        })
    }
    
}).listen("3000");

4.node的内置模块 - url+querystring(包含ajax)

url详解

//后端
const http = require("http")
const fs = require("fs")
const url = require("url") // 解析url地址的每一部分
const qs = require("querystring")
http.createServer((req, res) => {
    if (req.url !== "/favicon.ico") {
        let urlObj = url.parse(req.url, true)
            // console.log(urlObj)
            // 前台访问的路径
        if (urlObj.pathname === "/api") {
            ajax(req, res)
        } else {
            file(req, res)
        }
    }
}).listen("3000")

function ajax(req, res) {
    // 解析url
    let urlObj = url.parse(req.url, true)
    
  
    let str = "";
    req.on("data", (res) => {
        // 这里的res是数据片段 所以要拼接到一起
        str += res;
    })
    req.on("end", () => {
        let dataObj = "";
       // 判断是否是post请求
        if (str === "") {
            //    获取get方式传过来的数据
            dataObj = urlObj.query
        } else {
        	// 对post数据进行解析 不解析是buffer格式
            dataObj = qs.parse(str)
        }
        //对数据进行处理
        console.log(dataObj)
    })
}

function file(req, res) {
    fs.readFile("./www" + req.url, (err, data) => {
        if (err) {
            res.write("404")
        } else {
            res.write(data)
        }
        res.end();
    })
}

// 前端
<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style>

    </style>
</head>

<body>
    <h1>首页</h1>
    用户名:<input type="text" id="un"><br> 密码:
    <textarea name="" id="pw"></textarea><br>
    <input type="button" id="btn1" value="get请求-登录">
    <input type="button" id="btn2" value="post请求-注册">
</body>
<script src="jquery.js"></script>
<script>
    $("#btn1").click(function() {
        $.ajax({
            url: "http://localhost:3000/api",
            type: "get",
            data: {
                un: $("#un").val(),
                pw: $("#pw").val()
            },
            success: (res) => {
                console.log(res)
            }
        })
    })

    $("#btn2").click(function() {
        $.ajax({
            url: "http://localhost:3000/api",
            type: "post",
            data: {
                un: $("#un").val(),
                pw: $("#pw").val()
            },
            success: (res) => {
                console.log(res)
            }
        })
    })
</script>

</html>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值