当前位置:首页 » 《随便一记》 » 正文

node学习笔记——HTTP与URL模块_eyes++的博客

20 人参与  2022年05月21日 18:14  分类 : 《随便一记》  评论

点击全文阅读


HTTP模块

// 表示引入http模块
var http = require('http');

/*
    request     获取url传过来的信息
    response    给浏览器响应信息
*/
http.createServer(function (request, response) {
    // 设置响应头
    response.writeHead(200, {
        'Content-Type': 'text/plain'
    });
    // 表示给页面输出一句话并结束响应
    response.end('Hello World');
}).listen(8081);  // 开启的端口号

console.log('Server running at http://127.0.0.1:8081/');

在这里插入图片描述

const http = require("http");

/*
    req     获取客户端的请求信息
    res     给浏览器的响应信息
*/

http.createServer((req, res) => {
    console.log(req.url);  // 获取url

    // 设置响应头
    // 状态码是200,文件类型是html,字符集是utf8
    res.writeHead(200, {
        "Content-type": "text/html;charset=utf-8"
    });

    // 写入的页面内容
    res.write("hello nodejs");
    // 结束响应
    res.end();
}).listen(3000);  // 建议写3000以上,避免与其他应用冲突

在这里插入图片描述

URL

const url = require('url');

let api = "https://api.oick.cn/random/api.php?type=pc";

console.log(url.parse(api));

在这里插入图片描述

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

http.createServer((req, res) => {
    res.writeHead(200, {
        "Content-type": "text/html;charset=utf-8"
    });
    res.write(`
        <head><meta charset='UTF-8'></meta></head>
        <h1>hello nodejs</h1>
    `);

    if (req.url != '/favicon.ico') {
        let parameter = url.parse(req.url, true).query;
        console.log("姓名:" + parameter.name + " 年龄:" + parameter.age);
    }

    res.end();
}).listen(3000);

在这里插入图片描述


点击全文阅读


本文链接:http://zhangshiyu.com/post/40563.html

响应  信息  获取  
<< 上一篇 下一篇 >>

  • 评论(0)
  • 赞助本站

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

关于我们 | 我要投稿 | 免责申明

Copyright © 2020-2022 ZhangShiYu.com Rights Reserved.豫ICP备2022013469号-1