• express用POST传送数据

    // 服务端
    const express = require('express');  
    const app = express();  
    const port = 3000;  
    
    // 中间件,用于解析JSON请求体  
    app.use(express.json());  
    
    // 中间件,用于解析URL编码的请求体  
    app.use(express.urlencoded({ extended: true }));  
    
    // 定义POST路由
    // 获取body的内容,在控制台输出
    app.post('/submit', (req, res) => {  
        const data = req.body; // 获取请求体中的数据  
        console.log(data); // 打印数据到控制台  
        res.send('数据已接收'); // 向客户端发送内容  
    });  
    
    // 启动服务器  
    app.listen(port, () => {  
        console.log(`服务器正在运行在 http://localhost:${port}`);  
    });
    
    // 客户端
    // Fetch API向特定网址传送数据
    fetch('http://localhost:3000/submit', {  
        method: 'POST',  
        headers: {  
            'Content-Type': 'application/json',  
        },  
        // 数据body,将JavaScript object转换为JSON
        body: JSON.stringify({ name: 'Alice', age: 25 }),  
    })
    // 获取服务端响应
    .then(response => response.text())
    // 显示在console
    .then(data => console.log(data))  
    // Promise拒绝时,将错误信息输出到控制台
    .catch(error => console.error('Error:', error));
    

    运行客户端,console会得到:

    展开/折叠结果
    数据已接收
    

    此时,服务端的console可以得到:

    展开/折叠结果
    { name: 'Alice', age: 25 }
    

  • express的动态参数

    const express = require('express');
    const app = express();
    const port = 3000;
    
    // 进入http://localhost:3000/时,显示
    app.get('/', (req,res) => {
        res.send("Hello from the root directory!")
    });
    
    // 进入http://localhost:3000/cars/BMW/red,显示
    // 冒号后面是动态参数,可以更换
    app.get('/cars/:make/:color', (req,res) => {
        const {make, color} = req.params;
        res.send(`Car's make: ${make} - Car's color: ${color}`);
    });
    
    app.listen(port, () => {
        console.log(`Server is running on port ${port}`);
    });
    
    展开/折叠结果
    # http://localhost:3000/cars/BMW/red
    Car's make: BMW - Car's color: red
    
  • express的监听和get

    const express = require('express');   // 加载express 
    const app = express();   // 设置app为别名
    const port = 3000;   // 端口设置为3000
    
    // get方法,当浏览器访问时调用,一旦调用在console输出请求方法
    // 响应send方法,客户端浏览器显示string内容
    app.get("/", (req,res) => {
        console.log(`New request made: ${req.method}`);
        res.send("Hello from the server!");
    });
    
    // 监听localhost:端口
    app.listen(port, () => {
        console.log(`Server is running on port ${port}`);
    });
    
    展开/折叠结果
    Server is running on port 3000
    New request made: GET
    
  • JS的fetch()

    fetch("https://datahold.cn")
        .then((response) => {
            console.log(response);
        });
    

    fetch 是一个用于在 JavaScript 中进行网络请求的函数。它基于 Promise API,允许你轻松地发送 HTTP 请求并处理响应。

    展开/折叠结果
    Response {
      status: 200,
      statusText: 'OK',
      headers: Headers {
        server: 'nginx',
        date: 'Sat, 21 Dec 2024 13:04:22 GMT',
        'content-type': 'text/html; charset=UTF-8',
        'transfer-encoding': 'chunked',
        connection: 'keep-alive',
        'strict-transport-security': 'max-age=31536000',
        vary: 'Accept-Encoding, accept, content-type, cookie',
        'x-hacker': 'Want root?  Visit join.a8c.com and mention this header.',
        'host-header': 'WordPress.com',
        link: '; rel="https://api.w.org/", ; rel=shortlink',
        'last-modified': 'Sat, 21 Dec 2024 13:04:07 GMT',
        'cache-control': 'max-age=300, must-revalidate',
        'x-nananana': 'Batcache-Set',
        'content-encoding': 'br',
        'x-ac': '2.hhn _atomic_ams HIT',
        'alt-svc': 'h3=":443"; ma=86400'
      },
      body: ReadableStream { locked: false, state: 'readable', supportsBYOB: true },
      bodyUsed: false,
      ok: true,
      redirected: false,
      type: 'basic',
      url: 'https://datahold.cn/'
    }
    
  • node.js安装express

    npm install express
    

    简单的express应用:

    const express = require('express');  
    const app = express();  
    const PORT = 3000;  
    
    app.get('/', (req, res) => {  
        res.send('Hello World!');  
    });  
    
    app.listen(PORT, () => {  
        console.log(`Server is running on http://localhost:${PORT}`);  
    });  
    

    运行需要在cmd中,使用

    node app.js
    

    在浏览器中输入http://localhost:3000,可以得到结果

    展开/折叠结果
    Hello World!
    

  • JS加载外部模块文件

    两个文件放入相同的文件夹下,运行node script.js。运行需要安装Node.js。

    // abc.js
    const reminder = (message, event) => {
        const reason = 'Time for ' + event;
        return message + reason;
    };
    
    export default reminder;
    
    // script.js
    import reminder from "./abc.js";
    
    console.log(reminder("Wake up. ", "coding."));
    

    导入文件,使用import关键字。导出的内容用export关键字。

    展开/折叠结果
    Wake up. Time for coding.
    
  • Linux的shutdown

    NAME#名称
    shutdown – Halt, power off or reboot the machine
    #shutdown – 停止、关闭或重新启动计算机

    SYNOPSIS#概要

       shutdown [OPTIONS...] [TIME] [WALL...]
    

    DESCRIPTION#描述
    shutdown may be used to halt, power off, or reboot the machine.
    #shutdown 可用于停止、关闭或重新启动计算机。

       The first argument may be a time string (which is usually "now"). Optionally, this may be followed by a wall message to be sent to all logged-in users before going down.
       #第一个参数可以是时间字符串(通常是 “now”)。(可选)此消息后跟一条 wall 消息,该消息将在关闭之前发送给所有登录用户。
    
       The time string may either be in the format "hh:mm" for hour/minutes specifying the time to execute the 
    shutdown at, specified in 24h clock format. Alternatively it may be in the syntax "+m" referring to the specified number of minutes m from now.  "now" is an alias for "+0", i.e. for triggering an immediate
     shutdown. If no time argument is specified, "+1" is implied.
       #时间字符串可以采用 “hh:mm” 格式,表示小时/分钟,指定执行关机的时间,以 24 小时时钟格式指定。或者,它可能采用语法 “+m” 表示从现在开始的指定分钟数 m。 “now” 是 “+0” 的别名,即用于触发立即关闭。如果未指定 time 参数,则隐含 “+1”。
    
       Note that to specify a wall message you must specify a time argument, too.
       #请注意,要指定 wall 消息,还必须指定 time 参数。wall 消息会显示在屏幕上。
    
       If the time argument is used, 5 minutes before the system goes down the /run/nologin file is created to ensure that further logins shall not be allowed.
       #如果使用 time 参数,则在系统关闭前 5 分钟创建 /run/nologin 文件,以确保不允许进一步登录。
    

    OPTIONS#选项
    The following options are understood:
    #了解以下选项:

           --help
               Print a short help text and exit.
               #打印简短的帮助文件
    
           -H, --halt
               Halt the machine.
               #停止机器。
    
           -P, --poweroff
               Power the machine off (the default).
               #关闭设备电源(默认)。
    
           -r, --reboot
               Reboot the machine.
               #重启。
    
           -h
               The same as --poweroff, but does not override the action to take if it is "halt". E.g.  shutdown --reboot
               #与 --poweroff 相同,但不会覆盖 “halt” 时要执行的操作。例如 shutdown --reboot
               -h means "poweroff", but shutdown --halt -h means "halt".
               #-h 表示 “关机”,但 shutdown --halt -h 表示 “停止”。
    
           -k
               Do not halt, power off, or reboot, but just write the wall message.
               #不要停止、关闭电源或重新启动,而只需编写 wall 消息。
    
           --no-wall
               Do not send wall message before halt, power off, or reboot.
               #请勿在停止、关闭电源或重新启动之前发送 wall 消息。
    
           -c
               Cancel a pending shutdown. This may be used to cancel the effect of an invocation of shutdown with a time argument that is not "+0" or "now".
               #取消待处理的关闭。这可用于取消使用非 “+0” 或 “now” 的 time 参数调用 shutdown 的效果。
    
           --show
               Show a pending shutdown action and time if there is any.
               #显示待处理的关闭操作和时间(如果有)。
               Added in version 250.
               #在版本 250 中添加。
    

    EXIT STATUS#退出状态
    On success, 0 is returned, a non-zero failure code otherwise.
    #成功时,返回 0,否则返回非零失败代码。

    COMPATIBILITY#兼容性
    The shutdown command in previous init systems (including sysvinit) defaulted to single-user mode instead of powering off the machine. To change into single-user mode, use systemctl rescue instead.
    #以前的 init 系统(包括 sysvinit)中的 shutdown 命令默认为单用户模式,而不是关闭计算机电源。要更改为单用户模式,请改用 systemctl rescue。

    SEE ALSO#另见
    systemd(1), systemctl(1), halt(8), wall(1)

    systemd 255

  • JS类的继承

    extends关键字用于继承。相同的方法可以覆盖。注意类名首字母要大写。

    class ProgrammingLanguage{
        constructor(usesCurlies){
            this.usesCurlies=usesCurlies;
        }
        compile(){
            console.log("Compiling, curlies: "+this.usesCurlies);
        }
    }
    class R extends ProgrammingLanguage {}
    const lang1 = new R(true);
    lang1.compile();
    
    展开/折叠结果
    Compiling, curlies: true
    
    class Animal {
        pet(){
            console.log("wang wang wang");
        }
    }
    class Cat extends Animal {
        pet() {
            console.log("miao miao miao");
        }
    }
    const mindy = new Cat();
    mindy.pet();
    
    展开/折叠结果
    miao miao miao
    
  • JS的类、实例和方法

    类,相当于模板;实例相当于用模板生成的个体,个体继承类的所有属性和方法,个体之间相互独立;类中的函数function叫做方法,区别是在定义方法的时候无需加入关键字function

    class User{
        constructor(name) {
            this.name = name;
            this.isOnline = true;
        }
        sayHi() {
            console.log("Hi, I'm " + this.name);
        }
    }
    
    const user1 = new User("Zoc");
    const user2 = new User("John");
    
    user1.sayHi();
    user2.sayHi();
    
    展开/折叠结果
    Hi, I'm Zoc
    Hi, I'm John
    

  • JS的async关键字

    普通函数

    function normalFunction() {  
        return "Hello, World!";  
    }  
    
    let result = normalFunction(); 
    
    展开/折叠结果
    'Hello, World!'
    

    异步函数

    async function asyncFunction() {  
        return "Hello, World!";  
    }  
    
    let result = asyncFunction(); // result 是一个 Promise  
    result.then(resolve=> console.log(resolve)); 
    
    展开/折叠结果
    'Hello, World!'
    

    asyncFunction是一个异步函数,结果是一个Promise对象,当使用then的时候,返回成功的结果。这里只设置了resolve参数,可选参数reject没有使用。

    // 模拟一个异步操作的函数  
    function fetchData() {  
        return new Promise((resolve) => {  
            setTimeout(() => {  
                resolve("数据已成功获取!");  
            }, 2000); // 模拟延迟2秒  
        });  
    }  
    
    // 定义一个异步函数  
    async function getData() {  
        console.log("开始获取数据...");  
        
        // 使用 await 等待 fetchData() 的结果  
        const result = await fetchData();  
        
        console.log(result); // 输出获取到的数据  
    }  
    
    // 调用异步函数  
    getData();
    

    await只能在async函数内部使用。
    await后面跟随一个Promise,它会暂停执行,直到该Promise完成。