关于 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# 7系列,Part 4: Discards 弃元

    原文:https://blogs.msdn.microsoft.com/mazhou/2017/06/27/c-7-series-part-4-discards/ 有时我们想要忽略一个方法返回的值,特 ...

  2. 升级sharepoint2013遇到的坑

    现在要将sharepoint2010,ProjectServer2010升级到2016的版本,需要先升级到2013的版本. 按照官方文档,瞎搞将sharepoint2010升级到2013的版本,中间出 ...

  3. Redis简单命令(部分示例代码)

    一.redis文件夹下的可执行文件(文章尾部有示例代码) 可执行文件 作用 redis-server 启动redis redis-cli redis命令行工具 redis-benchmark 基准测试 ...

  4. C#开发微信小程序(三)

    导航:C#开发微信小程序系列 关于小程序项目结构,框架介绍,组件说明等,请查看微信小程序官方文档,关于以下贴出来的代码部分我只是截取了一些片段,方便说明问题,如果需要查看完整源代码,可以在我的项目库中 ...

  5. CentOS7安装ffmpeg

    首先在官网http://ffmpeg.org/download.html下载ffmpeg-4.2.1.tar.bz2 以下为安装步骤: 1.使用工具将源码包上传至Linux主机 2.解压源码包 进入该 ...

  6. python批量插入数据到es和读取es数据

    一.插入数据 1.首先准备类似如下数据 {"_type": "type1", "_id": 1, "_index": & ...

  7. RocketMq在SparkStreaming中的应用总结

    其实Rocketmq的给第三方的插件已经全了,如果大家有兴趣的话请移步https://github.com/apache/rocketmq-externals.本文主要是结合笔者已有的rmq在spar ...

  8. 几种设计良好结构以提高.NET应用性能的方法

    写在前面 设计良好的系统,除了架构层面的优良设计外,剩下的大部分就在于如何设计良好的代码,.NET提供了很多的类型,这些类型非常灵活,也非常好用,比如List,Dictionary.HashSet.S ...

  9. FCC---CSS Flexbox: Apply the flex-direction Property to Create Rows in the Tweet Embed

    The header and footer in the tweet embed example have child items that could be arranged as rows usi ...

  10. 页面中加入地图map

    1.首先要有密钥AK ,可以自己注册获取或复制别人的 .搜索百度地图API (http://lbsyun.baidu.com/apiconsole/key) 2.地图示例 <head> & ...