http://nodejs.cn/api/http.html
- HTTP 服务器和客户端,必须引入: require('http');
1、require 引入
- 如果有路径就在路径中查找(自定义的模块)
- 如果没有路径,就在node_modules中查找(npm安装的模块)
- 在没有路径,且没有node_modules的时候,会在node的安装目录中查找(一般用于系统模块)
2、服务器对象:
http.createServer() 快速搭建服务器(本机iP地址:127.0.0.1 域名:localhost)
let http = require("http");
http.createServer(()=>function{
console.log("内容")
}).listen(8081)
// .listen(8081)是监听要访问的端口。
// 参数是一个回调函数。启动之后,在浏览器访问这个端口,就可以执行回调函数
- 回调函数有两个参数,是返回给服务器的。
- 第一个参数:request 请求的时候传递的参数(简写req)
- 第二个参数:response 服务器返还的参数(简写res)
let http = require("http");
http.createServer((req,res)=>function{
res.write("index"); // 返还的内容
res.end(); // 表示结束。
// 可简写:
// res.end("index")
}).listen(8081)
3、路由
作用
(1)定义method(请求方式。比如:get/post)
(2)定义url规则(url的形式,比如:/api/list)
(3)定义输入(request body)和输出(response body)get :
(1)一般用于从服务器上获取数据
(2)测试可用浏览器直接访问post :
(1)一般用于向服务器传送数据
(2)测试需要借助工具—— postmanurl:判断获取的url中是否有参数,可截取,例:
const http = require('http');
const server = http.createServer((req, res) => {
const url = req.url
// 截取url链接中,问号前面的部分,并赋值给path
const path = url.split('?')[0] //后面判断路由的时候,直接使用path判断
const method = req.method
console.log('url:' + url)
console.log('method:' + method)
// 定义路由,模拟获取留言板
if (path === '/api/list' && method === 'GET') {
res.end('成功获取')
}
// res.end("ceshi")
res.end("404")
}).listen(3000)
4、postman
- 下载地址:https://www.postman.com/
- 作用:这里用于测试使用psot发送请求
-
安装:
win7 安装的时候,提示缺少Microsoft.NET, 直接点击安装即可。
安装
const http = require('http');
const server = http.createServer((req, res) => {
const url = req.url
const path = url.split('?')[0] //后面判断路由的时候,直接使用path判断
const method = req.method
console.log('url:' + url)
console.log('method:' + method)
// 定义路由,模拟获取留言板
if (path === '/api/list' && method === 'GET') {
res.end('成功获取')
}
// 添加post方式,匹配的路由判断 ,模拟创建留言
if (path === '/api/create' && method === 'POST') {
res.end('POST成功')
}
// res.end("ceshi")
res.end("404")
}).listen(3000)
5、querystring
-
形式:
(1)在url中,问号(?)后面的都是querystring,就得说url的参数部分。例:
querystring
(2)若是有多个参数,每个参数直接使用"&"分隔,参数是key=value的形式 -
作用以及如何使用:
(1)输入不同的参数,可访问不同的页面,不同的部分。
(2)服务端拿到querystring,根据不同的querystring返回不同的内容。querystring改变的时候,对应的内容发生变化
(3)注意: url中的问号,使用英文格式的,不然获取的url中有EF%BC%等,例:
问号格式错误
(4)测试:
image.png
-
querystring.parse
(1) 引入 querystring模块:const querystring = require('querystring');
(2) 使用querystring.parse
能够将获取的a = 100,转换为{a:100}的格式,例:
parse
(3)url的hash,如下,"#"号后面的部分,不能使用parse获取,因为hash无法传递到服务端。
-
结构化与非结构化 (简单了解即可)
(1)结构化的数据,易通过程序访问和分析,比如:对象、数组。
(2)非结构话的,不易通过程序分析,比如:字符串
(3)所以一般建议,尽量使用结构化数据
6、使用response返回数据
- 返回json格式数据
(1)设置appLication/json
res.writeHead(200, { 'Content-type': 'appLication/json' })
(2)get请求,返回json
(3)post请求,返回json
(4)返回字符串
res.writeHead(404, { 'Content-type': 'text/plain' })
(5)整体代码参考如下:
const http = require('http')
const querystring = require('querystring')
const server = http.createServer((req, res) => {
const url = req.url
const path = url.split('?')[0]
const queryStr = url.split('?')[1]
const method = req.method
const query = querystring.parse(queryStr)
if (path === '/api/list' && method === 'GET') {
const result = {
errno: 0,
data: [
{ user: '张三', content: "留言1" },
{ user: '张四', content: "留言2" }
]
}
// res.end('成功获取')
res.writeHead(200, { 'Content-type': 'appLication/json' })
res.end(JSON.stringify(result))
}
if (path === '/api/create' && method === 'POST') {
// res.end('POST成功')
const result = {
errno: 0,
message: '创建成功'
}
res.writeHead(200, { 'Content-type': 'appLication/json' })
res.end(JSON.stringify(result))
}
// 页面返回字符串
res.writeHead(404, { 'Content-type': 'text/plain' })
res.end("404")
}).listen(3000)
-
返回html格式数据(了解即可,不使用)
(1)设置Content-type:text/html
(2)如下:
返回html格式
7、使用request返回数据
- 流:
-
下载时:
(1)source(服务端),dest(前端/客服端)
水相当于下载的数据,水管,相当于网络
image.png
(2)服务端 res.end(...),自动以流的形式返回给浏览器,浏览器识别到流,会持续接收信息。接收完之后,会显示或处理。(比如:视频一段段的加载显示)
- 上传时:
(1)source前端,dest服务端
水相当于上传的数据,水管,相当于网络 - 识别“流”,并输出数据:
const http = require('http')
const querystring = require('querystring')
const server = http.createServer((req, res) => {
const url = req.url
const path = url.split('?')[0]
const method = req.method
// const queryStr = url.split('?')[1]
// const query = querystring.parse(queryStr)
console.log('path:' + path)
console.log('method:' + method)
if (path === '/api/abc' && method === 'POST') {
// POST请求。传递json数据
// const result = {
// errno: 0,
// message: '创建成功'
// }
// res.writeHead(200, { "Content-type": 'appLication/json' })
// res.end(JSON.stringify(result))
// 服务端,如何去识别并接收"流"
let bodyStr = ''
req.on('data', chunk => {
// chunk :"流"的每一段数据
bodyStr += chunk.toString() // 每次流一段,将其累加,
})
// 服务端,如何知道"流"流完了,完了之后,会执行end方法。
req.on('end', () => {
console.log('bodyStr:', bodyStr)
res.end('接收完')
})
// const result = {
// errno: 0,
// message: '创建成功'
// }
// res.writeHead(200, { 'Content-type': 'appLication/json' })
// res.end(JSON.stringify(result))
}
// res.end('POST成功33')
}).listen(3000)