关于 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. C# MD5加密字符串

    /// <summary> /// 用MD5加密字符串,可选择生成16位或者32位的加密字符串 /// </summary> /// <param name=" ...

  2. 使用littlefs-fuse在PC端调试littlefs文件系统

    背景 littlefs是arm面向嵌入式设备推出的一款掉电安全的小型文件系统,具有抗掉电,动态磨损均衡,RAM/ROM需求少等特点,具体介绍可见 https://github.com/ARMmbed/ ...

  3. 面试连环炮系列(二十三): StringBuffer与StringBuild的区别

    StringBuffer与StringBuild的区别 频繁修改字符串时,建议使用StringBuffer和StringBuilder类.StringBuilder相较于StringBuffer有速度 ...

  4. 在.NET Core控制台中使用依赖注入

    本文介绍如何在控制台应用程序中使用微软提供的依赖注入功能,掌握控制台中的用法后,可以扩展到构建windows服务中. 创建控制台应用程序 添加DependencyInjection的引用 Instal ...

  5. JS---封装getScroll函数 & 案例:固定导航栏

    封装getScroll函数 1. 获取页面向上或者向左卷曲出去的距离的值 2. 浏览器的滚动事件 function getScroll() { return { left: window.pageXO ...

  6. JS---另一个定时器:一次性的

    之前学的定时器:setInterval和清除定时器 clearInterval(定时器id); //常用的,反复的执行 window.setInterval(function () { alert(& ...

  7. windows下MySQL解压版安装

    MySQL的安装 一.前期准备 获取MySQL解压版安装包(本文使用的是 [mysql-5.7.28-winx64.zip]版本) 获取方式: 通过官网下载,官方下载地址:“https://dev.m ...

  8. 黑苹果 macOS 10.13.6 17G66 安装 nVidia WebDriver

    目前很多N卡的WebDriver已经不支持macOS 10.14了,只能停留在10.13.6,苹果AppStore下载的 macOS High Sierra 10.13.6 版本号是17G66,遗憾的 ...

  9. ASP.NET Core身份验证

    asp.net core 身份验证 本文旨在演示如果使用内置的 identity 实现 asp.net core 的身份验证,不会进行其它扩展.本文将通过最简单的代码演示如何进行登录和身份验证操作. ...

  10. js的cookies及html5的localStorage、sessionStorage

    1.首先,理解什么是cookies? cookies:存储在客户端,数据量小的,会过期的数据,以字符串形式存储 cookie操作代码示例: <script> window.onload = ...