node.js

发布时间 2023-12-27 18:28:20作者: 波波波维奇~
  • npm 安装的包,dependences 下的包和 devDependences 下得包有什么区别

    dependences:生产环境使用的包,代码运行必要的包,没有包运行时会报错,如lodash

    decDdpendences:开发环境使用的包,代码运行不必要,没要包代码也能跑,使用这些包的目的是方便开发人员做项目,如webpack、nodemon等,项目上线之后这些包就没用了

  • 软件包的安装位置

    本地安装 / 局部安装:npm install 包名,被安装在当前文件夹下得 node_modules 子文件夹下,只有当前项目能用(推荐使用)

    全局安装:npm install 包名 -g ,包将装在全局的位置,可以使用 npm root -g 查看全局的位置

  • 查看已经安装的包:npm list
  • 安装包版本规则:

    默认情况下,npm install --save 下载的都是最新版本,并且会在 package.json 文件里登记一个最优版本号

    ~ 会匹配最新的小版本依赖包,比如 ~1.2.3 会匹配所有的 1.2.x 版本,不包括 1.3.0

    ^ 会匹配最新的大版本依赖包,比如 ^1.2.3 会匹配所有的 1.x.x 的包,包括 1.3.0,但是不包括 2.0.0

    直接写 * 会安装最新版本的依赖包

    前面不加任何符号代表安装特定的版本

  • 卸载包

    局部安装卸载:npm uninstall 包名

    全局安装卸载:npm uninstall -g 包名

 

  • commonjs 模块化

    module.exports 导出,require() 导入,主要用于 node.js 开发

  • 模块的三种分类

    1. 系统自带模块,不用安装,直接使用,如 http

    2. npm 包,需要安装之后才能使用,如 lodash

    3. 自定义模块,自己写的,不用安装

    Tips: require 会先找系统自带的,再找 npm 包,最后再自定义

  • commonjs 和 ES module 的区别

    1. 两者语法不一样

    2. commonjs 是执行时引入的,动态的,意味着可以写在任何位置

    3. ES6 Module 是打包时引入的,静态的,必须卸载第一行,因为要先引入

  • nodejs 和 前端 js

    都是使用 JS 语法

    前端 JS 使用 浏览器提供的 WEBAPI,前端JS = ES + DOM +BOM

    nodejs 使用 nodejs API,nodejs = ES + nodejs API

  • nodejs 处理 http 请求
    • req(request)和 res(response),请求和响应,是 http 请求的关键
// commonjs 引入模块, node自带模块, 不需要安装
const http = require("http");

// createServer可以创建一个服务, 不过需要接收一个回调函数做参数
//createServer有两个形参,一个是 req(请求),一个是 res(响应)
const server = http.createServer((req,res) => {
    //req.url() 可以获取请求的 url
    const url = req.url;

    //res.end() 可以设置返回给前端的信息 
    res.end("the url is" + url);
});
// 监听3000端口
server.listen(3000);
// 输出提示
console.log("http请求已经被监听, 3000端口, 请访问: http://localhost:3000");

 

    • 定义 GET 路由
// commonjs 引入模块, node自带模块, 不需要安装
const http = require("http");

// createServer可以创建一个服务, 不过需要接收一个回调函数做参数
//createServer有两个形参,一个是 req(请求),一个是 res(响应)
const server = http.createServer((req,res) => {
    //req.url() 可以获取请求的 url
    const url = req.url;
    //req.method() 可与用来获取 method
    const method = req.method;
    //res.end() 可以设置返回给前端的信息 
    res.end(`url is ${url}, method is ${method}`);
});
// 监听3000端口
server.listen(3000);
// 输出提示
console.log("http请求已经被监听, 3000端口, 请访问: http://localhost:3000");

 

    判断 method 和 url 是否正确

// commonjs 引入模块, node自带模块, 不需要安装
const http = require("http");

// createServer可以创建一个服务, 不过需要接收一个回调函数做参数
//createServer有两个形参,一个是 req(请求),一个是 res(响应)
const server = http.createServer((req,res) => {
    //req.url() 可以获取请求的 url
    const url = req.url;
    //判断条件改变,避免url带参数报错,对于带参数的路径,需要加上这个
    const path = url.split("?")[0];
    //req.method() 可与用来获取 method
    const method = req.method;

    //判断 method 和 url 是否正确
    if( path === "/api/list" && method.toUpperCase() === "GET"){
        res.end(`url is ${url}, method is ${method}`);
    }else{
        res.end(`请求错误,请确认路径和方法是否正确`);
    }
});
// 监听3000端口
server.listen(3000);
// 输出提示
console.log("http请求已经被监听, 3000端口, 请访问: http://localhost:3000");

 

    • 定义 POST 路由,在 GET路由上多加一个判断
// commonjs 引入模块, node自带模块, 不需要安装
const http = require("http");

// createServer可以创建一个服务, 不过需要接收一个回调函数做参数
//createServer有两个形参,一个是 req(请求),一个是 res(响应)
const server = http.createServer((req,res) => {
    //req.url() 可以获取请求的 url
    const url = req.url;
    //判断条件改变,避免url带参数报错
    const path = url.split("?")[0];
    //req.method() 可与用来获取 method
    const method = req.method;

    //判断 method 和 url 是否正确
    if( path === "/api/list" && method.toUpperCase() === "GET"){
        res.end(`您正在请求留言列表接口`);
    }else if( path === "/api/create" && method.toUpperCase() === "POST"){
        res.end(`您正在请求提交留言接口`);
    }else{
        res.end(`请求错误,请确认路径和方法是否正确`);
    }
});
// 监听3000端口
server.listen(3000);
// 输出提示
console.log("http请求已经被监听, 3000端口, 请访问: http://localhost:3000");

 

 

  • querystring:url 中 ?后的参数称为querystring,也叫做 url 参数

    querystring 转对象:

// 引入querystring模块
const querystring = require("querystring");
consy http = require("http");

// 创建一个http服务
const server = http.createServer((req, res) => {
  // querystring转对象
  const queryObj = querystring.parse(queryStr);

  // 得到的结果 { number: '100', sort: 'desc' }
});

 

    hash 路由:http://xxx.com/index.html/#/home

    Tips:hash 路由不能由服务端获取,因为 require.url 只能获取到 /index.html/,hash 路由的相关数据可以使用 ajax 请求接口获取

  • 使用 res 返回数据
//引入 commonjs 模块
const http = require("http");

//创建一个服务
const server = http.createServer((req,res) => {
    //获取url
    const url = req.url
    //获取路径
    const path = url.split("?")[0];
    //获取方法
    const method = req.method;
    //判断路由满足条件
    if( path === "/api/list" && method.toUpperCase() === "GET"){
        //定义返回的请求头
        res.writeHead(200,{"Content-type": "application/json"});
        //定义返回体,包含错误码,返回数据和返回信息
        const responseBody = {
            errno: 0,
            data: [
                {username: '张三', content: '张三 真帅!'},
                {username: '李四', content: '李四 真帅!'},
                {username: '王五', content: '王五 真帅!'},
                {username: '赵六', content: '赵六 真帅!'}
            ],
            msg: 'success'
        }
        //res.end只能返回字符串,需要先将对象转换为字符串
        res.end(JSON.stringify(responseBody));
    }else if( path === "/api/create" && method.toUpperCase() === "POST"){
        //定义请求头
        res.writeHead(200,{"Content-type": "application/json"});
        //定义返回体
        const responseBody = {
            errno: 0,
            data:{ id: 1},
            msg: 'success'
        }
        //res.end的参数只能是数组
        res.end(JSON.stringify(responseBody));
    }else{
        //res.writeHead(404, {"Content-type": "text/plain"});
        res.end("404 Not Found");
    }
})
server.listen(3000);
console.log("正在监听3000端口……")

 

  • res 返回 HTML(比如 404网页 ,可以自己制作)
//只需将返回的形式改成html,再吧html代码写进res.end即可
else{
        res.writeHead(404, {"Content-type": "text/html"});
        res.end(`<!DOCTYPE html>
        <html lang="en">
            <head>
                <meta charset="UTF-8" />
                <meta http-equiv="X-UA-Compatible" content="IE=edge" />
                <meta name="viewport" content="width=device-width, initial-scale=1.0" />
                <title>Document</title>
                <style>
                    * {
                        padding: 0;
                        margin: 0;
                    }
                    img {
                        width: 100%;
                    }
                </style>
            </head>
            <body>
                <img src="https://markdown-1253389072.cos.ap-nanjing.myqcloud.com/202203191544993.png" alt="" />
            </body>
        </html>`);
    }

 

  • 发送留言的接口
//引入 commonjs 模块
const http = require("http");

//创建一个服务
const server = http.createServer((req, res) => {
    //获取url
    const url = req.url
    //获取路径
    const path = url.split("?")[0];
    //获取方法
    const method = req.method;


    //判断路由满足条件
    if (path === "/api/list" && method.toUpperCase() === "GET") {
        //定义返回的请求头
        res.writeHead(200, { "Content-type": "application/json" });
        //定义返回体,包含错误码,返回数据和返回信息
        const responseBody = {
            errno: 0,
            data: [
                { username: '张三', content: '张三 真帅!' },
                { username: '李四', content: '李四 真帅!' },
                { username: '王五', content: '王五 真帅!' },
                { username: '赵六', content: '赵六 真帅!' }
            ],
            msg: 'success'
        }
        //res.end只能返回字符串,需要先将对象转换为字符串
        res.end(JSON.stringify(responseBody));
    } else if (path === "/api/create" && method.toUpperCase() === "POST") {
        let bodyString = '';
        //获取数据
        req.on("data", (chunk) => {
            bodyString += chunk.toString();
        })
        req.on("end", () => {
            let responseBody = {};
            //定义请求头
            res.writeHead(200, { "Content-type": "application/json" });
            //判断数据是否是json格式
            if (req.headers["content-type"] === "application/json") {
                //将字符串转为对象
                const bodyObj = JSON.parse(bodyString);
                //定义返回体
                responseBody = {
                    errno: 0,
                    data: { id: 1, ...bodyObj },
                    msg: '留言创建成功!'
                }
            }else{
                responseBody = {
                    errno: 1,
                    msg: "携带数据的格式不正确!"
                }
            }
            //res.end的参数只能是数组
            res.end(JSON.stringify(responseBody));
        })
    } else {
        res.writeHead(404, { "Content-type": "text/html" });
        res.end(`<!DOCTYPE html>
        <html lang="en">
            <head>
                <meta charset="UTF-8" />
                <meta http-equiv="X-UA-Compatible" content="IE=edge" />
                <meta name="viewport" content="width=device-width, initial-scale=1.0" />
                <title>Document</title>
                <style>
                    * {
                        padding: 0;
                        margin: 0;
                    }
                    img {
                        width: 100%;
                    }
                </style>
            </head>
            <body>
                <img src="https://markdown-1253389072.cos.ap-nanjing.myqcloud.com/202203191544993.png" alt="" />
            </body>
        </html>`);
    }
})
server.listen(3000);
console.log("正在监听3000端口……")