关于 node,总是断断续续的学一点,也只能在本地自己模拟实战,相信总会有实战的一天~~

  • http 作为服务端,开启服务,处理路由,响应等
  • http 作为客户端,发送请求
  • http、https、http2 开启服务

作为服务端

  1. 开启服务,有两种方式

方式1

const http = require('http')

// 开启服务
var server = http.createServer(function (req, res) {
// 开启服务后具体做什么
res.end('hello world')
}).listen(3000);

方式2

const http = require('http')
const server = new http.Server()
// node 中的服务都是继承 eventemit // 开启服务
server.on('request', function ()
// 开启服务后具体做什么
res.end('hello world')
})
server.listen(3000)
  1. 路由

路由的原理:根据路径去判断

const http = require('http')
const server = new http.Server();
server.on('request', function () {
var path = req.url;
switch (path) {
case '/':
res.end('this is index');
// res.end('<a href="./second">second</a>');
break;
case '/second':
res.end('this is second');
break;
default:
res.end('404');
break;
}
})
server.listen(3000)
  1. 获取请求头信息、设置响应头
const http = require('http')
const server = new http.Server();
server.on('request', function () { // 设置响应头:setHeader() / writeHead()
// setHeader 设置多次,每次一个
res.setHeader('xxx', 'yyy');
res.setHeader('aaa', 'yyy');
res.setHeader('bbb', 'yyy'); // writeHead 只能设置一次,多个,会合并setHeader中的信息,同名优先级高
res.writHead(200, {
'content-type': 'text/html;charset=utf-8', //'text/plain;charset=utf-8'
'ccc': 'yyy',
'aaa': 'aaa'
}) // 需要先设置响应头,再设置res.end,需要先设置setHeader,再设置res.writHead // 请求头信息
console.log(req.httpVersion)
console.log(req.method)
console.log(req.url)
console.log(http.STATUS_CODES) // 比如根据请求头进行:token处理
var token = md5(req.url + req.headers['time'] + 'dsjaongaoeng');
if (req.headers['token'] == token) {
res.end()
} else {
res.end()
} })
server.listen(3000)
  1. 常用监听事件
const http = require('http')
const server = new http.Server();
server.on('request', function () { // 请求监听
// 每次有数据过来
req.on('data', function (chunk) { })
// 整个数据传输完毕
req.on('end', function () { }) // 响应监听
res.on('finish', function () {
console.log('响应已发送')
}) res.on('timeout', function () {
res.end('服务器忙')
})
res.setTimeout(3000) }) // 连接
server.on('connection', function () { }) // 错误处理
server.on('error', function (err) {
console.log(err.code)
}) // 超时 2000 ms
server.setTimeout(2000, function () {
console.log('超时')
}) server.listen(3000)
  1. 接受 get 和 post 请求
const http = require('http')
const url = require('url')
const server = new http.Server();
server.on('request', function () { // get 参数,放在url中,不会触发 data
var params = url.parse(req.url, true).query;
// post 参数,在请求体中,会触发 data
var body = ""
req.on('data', function (thunk) {
body += chunk
})
req.end('end', function () {
console.log(body)
}); }) server.listen(3000)

http 作为客户端

  1. 发送请求:request 发送 post 请求,get 发送 get 请求
const http = require('http')

const option = {
hostname: '127.0.0.1',
port: 3000,
method: 'POST',
path: '/', // 可不写,默认到首页
headers: {
'Content-Type': 'application/json'
}
}
// post
var req = http.request(option, function (res) {
// 接收响应
var body = ''
res.on('data', function (chunk) {
body += chunk
})
res.on('end', function () {
console.log(body)
})
}); var postJson = '{"a": 123, "b": 456}'
req.write(postJson)
req.end(); // 结束请求 // get
http.get('http://localhost:3000/?a=123', function (req) {
// 接收响应
var body = ''
res.on('data', function (chunk) {
body += chunk
})
res.on('end', function () {
console.log(body)
})
});
  1. 设置请求头和响应头
const http = require('http')

const option = {
hostname: '127.0.0.1',
port: 3000,
method: 'POST',
path: '/', // 可不写,默认到首页
headers: { // 可在此设置请求头
'Content-Type': 'application/json'
}
}
// post
var req = http.request(option, function (res) {
// 避免乱码
res.setEncoding('utf-8')
// 获取响应头
console.log(res.headers)
console.log(res.statusCode) // 接收响应
var body = ''
res.on('data', function (chunk) {
body += chunk
})
res.on('end', function () {
console.log(body)
})
}); var postJson = '{"a": 123, "b": 456}'
// 设置请求头
req.setHeader('xx', 'aaa') req.write(postJson)
req.end(); // 结束请求

http、https、http2 开启服务的区别

  1. http
const http = require('http')
const options = {}
// options 可不传
http.createServer(options, (req, res) => {
res.end()
}).listen(3000) http.createServer((req, res) => {
res.end()
}).listen(3000)
  1. https
const https = require('https')
const fs = require('fs') const options = {
key: fs.readFileSync('./privatekey.pem'), // 私钥
cert: fs.readFileSync('./certificate.pem') // 公钥
} https.createServer(options, (req, res) => {
res.end()
}).listen(3000)
  1. http2
const http2 = require('http2')
const fs = require('fs') const options = {
key: fs.readFileSync('./privatekey.pem'), // 私钥
cert: fs.readFileSync('./certificate.pem') // 公钥
} http2.createSecureServer(options, (req, res) => {
res.end()
}).listen(3000)

最后,关于 node 还有很多需要学的,比如 文件(fs)系统,及 node 使用数据库,还有框架(express、koa2,曾经学过,不用忘的好快),服务器部署等,加油!。

node http 模块 常用知识点记录的更多相关文章

  1. atitit 商业项目常用模块技术知识点 v3 qc29

    atitit 商业项目常用模块技术知识点 v3 qc29 条码二维码barcodebarcode 条码二维码qrcodeqrcode 条码二维码dm码生成与识别 条码二维码pdf147码 条码二维码z ...

  2. Node.js process 模块常用属性和方法

    Node.js是常用的Javascript运行环境,本文和大家发分享的主要是Node.js中process 模块的常用属性和方法,希望通过本文的分享,对大家学习Node.js http://www.m ...

  3. BIOS备忘录之EC常用知识点

    BIOS工程师眼中常用的EC知识点汇总: EC的硬件架构 EC硬件结构上主要分为两部分:Host Domain和EC Domain Host Domain就是通过LPC与CPU通信的部分(LPC部分需 ...

  4. Developer - 如何自我保证Node.js模块质量

    组里正在做SaaS产品,其中一些模块(Module)是Node.js实现,这里我们主要使用Node.js实现Web Server来提供服务. 在做SaaS项目之前,组里的开发模式是传统的Deverlo ...

  5. Node.js学习(第二章:node核心模块--fs)

    前言 Node.js中赋予了JavaScript很多在浏览器中没有的能力,譬如:文件读写,创建http服务器等等,今天我们就来看看在node中怎样用JavaScript进行文件的读写操作. 读文件 我 ...

  6. C#知识点记录

    用于记录C#知识要点. 参考:CLR via C#.C#并发编程.MSDN.百度 记录方式:读每本书,先看一遍,然后第二遍的时候,写笔记. CLR:公共语言运行时(Common Language Ru ...

  7. DB2_SQL_常用知识点&实践

    DB2_SQL_常用知识点&实践 一.删除表中的数据(delete或truncate) 1 truncate table T_USER immediate; 说明:Truncate是一个能够快 ...

  8. Oracle EBS BOM模块常用表结构

    表名: bom.bom_bill_of_materials  说明: BOM清单父项目  BILL_SEQUENCE_ID NUMBER 清单序号(关键字)ASSEMBLY_ITEM_ID NUMBE ...

  9. SAP FI CO模块常用事务代码

                                                                                                        ...

随机推荐

  1. django甜甜的弹窗

    GitHub中甜甜的弹窗地址: https://github.com/lipis/bootstrap-sweetalert 直接简单粗暴选择右下角的download,下载到本地一份文件 小猿取经中的相 ...

  2. 常见面试题之*args 和 **kwargs 的使用

    def self_max(*args,**kwargs): print(args) print(kwargs) self_max(1,2,3,4,5,6,7,x=6,y=8,z=80,e=50) 输出 ...

  3. 一起学Spring之Web基础篇

    概述 在日常的开发中Web项目集成Spring框架,已经越来越重要,而Spring框架已经成为web开发的主流框架之一.本文主要讲解Java开发Web项目集成Spring框架的简单使用,以及使用Spr ...

  4. Oracle 创建用户,赋予指定表名/视图只读权限

    步骤指南 创建用户 格式:; 语法:create user 用户名 identified by 密码; 注:密码不行的话,前后加(单引号):' create user TEST identified ...

  5. 【数据库】SQLite3常用命令

    版权声明:本文为博主原创文章,转载请注明出处. https://www.cnblogs.com/YaoYing/ 打开SQLite3文件 sqlite3 student.db //打开student. ...

  6. 《C#并发编程经典实例》学习笔记—3.1 数据的并行处理

    问题 有一批数据,需要对每个元素进行相同的操作.该操作是计算密集型的,需要耗费一定的时间. 解决方案 常见的操作可以粗略分为 计算密集型操作 和 IO密集型操作.计算密集型操作主要是依赖于CPU计算, ...

  7. SpringMVC通过Redis实现缓存主页

    这里说的缓存只是为了提供一些动态的界面没办法作静态化的界面来减少数据库的访问压力,如果能够做静态化的话的还是采用nginx来做界面的静态化,这样可以承受高并发的访问能力. 好了,废话少说直接看实现代码 ...

  8. dpwwn: 1 Vulnhub Walkthrough

    主机层面扫描: ╰─ nmap -p1-65535 -sV -A 10.10.202.130 22/tcp   open  ssh     OpenSSH 7.4 (protocol 2.0) 80/ ...

  9. git命令行的颜色配置

    Git颜色branch,diff,interactive,status配置,git终端配置颜色,git命令行高亮 Git默认的输出是单一颜色的,感觉很不容易阅读,Git支持用多种颜色来显示其输出的信息 ...

  10. C#后台架构师成长之路-基础体系篇章大纲

    如下基础知识点,如果不熟透,以后容易弄笑话..... 1. 常用数据类型:整型:int .浮点型:double.布尔型:bool.... 2. 变量命名规范.赋值基础语法.数据类型的转换.运算符和选择 ...