【前端知识】Node——http模块&url模块的常用操作

一、创建简易Server

javascript 复制代码
const http = require('http');
const URL = require('url');

const HTTP_PORT = 8088;

const server = http.createServer((req, res) => {
    // req:request请求对象,包含请求相关的信息;
    // res:response响应对象,包含我们要发送给客户端的信息;
    const { headers, method, url } = req;
    console.log( headers, method, url);
});

server.listen(HTTP_PORT, () => {
    console.log(`🚀 Outman 服务器已启动,端口:${HTTP_PORT}`);
})

二、url相关处理

javascript 复制代码
const http = require('http');
const URL = require('url');

const HTTP_PORT = 8088;

const server = http.createServer((req, res) => {
    // req:request请求对象,包含请求相关的信息;
    // res:response响应对象,包含我们要发送给客户端的信息;
    const { headers, method, url } = req;
    console.log( headers, method, url);

    // url处理
    if(url === '/login'){
        res.end('hello outman');
    }else if(url === '/products'){
        res.end('products list');
    }else{
        res.end('error request');
    }

    // url带参解析(GET)
    const parseInfo = URL.parse(req.url);
    console.log(parseInfo);
    const { pathname, query } = URL.parse(req.url);
    const queryObj = URL.parse(query);
    console.log(pathname, queryObj);
});

server.listen(HTTP_PORT, () => {
    console.log(`🚀 Outman 服务器已启动,端口:${HTTP_PORT}`);
})

三、请求配置与监听

javascript 复制代码
const http = require('http');
const URL = require('url');

const HTTP_PORT = 8088;

const server = http.createServer((req, res) => {
    // req:request请求对象,包含请求相关的信息;
    // res:response响应对象,包含我们要发送给客户端的信息;
    const { headers, method, url } = req;
    console.log( headers, method, url);

    // req 配置 & 监听
    req.setEncoding('utf-8');
    // 监听获取body中的参数(POST)
    req.on('data', (data) => {
        console.log('data', data);
        const { username, password } = JSON.parse(data);
        console.log(username, password);
    });
    req.on('end', () => {
        console.log('传输结束');
    });
    res.end('outman msg')
});

server.listen(HTTP_PORT, () => {
    console.log(`🚀 Outman 服务器已启动,端口:${HTTP_PORT}`);
})

四、常用HTTP CODE

HTTP状态码 状态描述 信息说明
200 OK 请求成功
201 Created POST请求,创建新的资源
301 Moved Pemanently 请求资源的URL已经修改,响应中会给出新的URL
400 Bad Request 客户端的错误,服务器无法或者不进行处理
401 Unauthorized 未授权的错误,必须携带请求的身份信息
403 Forbidden 客户端没有权限访问,被拒接
404 Not Found 服务器找不到请求的资源
500 Internal Server Error 服务器遇到了不知道如何处理的情况
503 Service Unavailable 服务器不可用,可能处理维护或者重载状态,暂时无法访问
相关推荐
林晓lx27 分钟前
使用Git钩子+ husky + lint语法检查提高前端项目代码质量
前端·git·gitlab·源代码管理
王同学要变强1 小时前
【深入学习Vue丨第二篇】构建动态Web应用的基础
前端·vue.js·学习
程序定小飞1 小时前
基于springboot的web的音乐网站开发与设计
java·前端·数据库·vue.js·spring boot·后端·spring
Hello_WOAIAI1 小时前
2.4 python装饰器在 Web 框架和测试中的实战应用
开发语言·前端·python
FinClip1 小时前
凡泰极客亮相香港金融科技周,AI助力全球企业构建超级应用
前端
阿四2 小时前
【Nextjs】为什么server action中在try/catch内写redirect操作会跳转失败?
前端·next.js
申阳2 小时前
Day 6:04. 基于Nuxt开发博客项目-LOGO生成以及ICON图标引入
前端·后端·程序员
中国lanwp2 小时前
npm中@your-company:registry 和 registry 的区别
前端·npm·node.js
Bacon2 小时前
Electron 应用商店:开箱即用工具集成方案
前端·github
行走的陀螺仪2 小时前
uni-app + Vue3 实现折叠文本(超出省略 + 展开收起)
前端·javascript·css·uni-app·vue3