http://nodejs.cn/api/http.html
- HTTP 服務(wù)器和客戶端洒沦,必須引入: require('http')穷吮;
1宣增、require 引入
- 如果有路徑就在路徑中查找(自定義的模塊)
- 如果沒有路徑诲祸,就在node_modules中查找(npm安裝的模塊)
- 在沒有路徑,且沒有node_modules的時候掀序,會在node的安裝目錄中查找(一般用于系統(tǒng)模塊)
2帆焕、服務(wù)器對象:
http.createServer() 快速搭建服務(wù)器(本機(jī)iP地址:127.0.0.1 域名:localhost)
let http = require("http");
http.createServer(()=>function{
console.log("內(nèi)容")
}).listen(8081)
// .listen(8081)是監(jiān)聽要訪問的端口。
// 參數(shù)是一個回調(diào)函數(shù)不恭。啟動之后叶雹,在瀏覽器訪問這個端口,就可以執(zhí)行回調(diào)函數(shù)
- 回調(diào)函數(shù)有兩個參數(shù)县袱,是返回給服務(wù)器的浑娜。
- 第一個參數(shù):request 請求的時候傳遞的參數(shù)(簡寫req)
- 第二個參數(shù):response 服務(wù)器返還的參數(shù)(簡寫res)
let http = require("http");
http.createServer((req,res)=>function{
res.write("index"); // 返還的內(nèi)容
res.end(); // 表示結(jié)束。
// 可簡寫:
// res.end("index")
}).listen(8081)
3式散、路由
作用
(1)定義method(請求方式筋遭。比如:get/post)
(2)定義url規(guī)則(url的形式,比如:/api/list)
(3)定義輸入(request body)和輸出(response body)get :
(1)一般用于從服務(wù)器上獲取數(shù)據(jù)
(2)測試可用瀏覽器直接訪問post :
(1)一般用于向服務(wù)器傳送數(shù)據(jù)
(2)測試需要借助工具—— postmanurl:判斷獲取的url中是否有參數(shù)暴拄,可截取漓滔,例:
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發(fā)送請求
-
安裝:
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方式,匹配的路由判斷 楣号,模擬創(chuàng)建留言
if (path === '/api/create' && method === 'POST') {
res.end('POST成功')
}
// res.end("ceshi")
res.end("404")
}).listen(3000)
5最易、querystring
-
形式:
(1)在url中,問號(炫狱?)后面的都是querystring藻懒,就得說url的參數(shù)部分。例:
querystring
(2)若是有多個參數(shù)视译,每個參數(shù)直接使用"&"分隔嬉荆,參數(shù)是key=value的形式 -
作用以及如何使用:
(1)輸入不同的參數(shù),可訪問不同的頁面憎亚,不同的部分员寇。
(2)服務(wù)端拿到querystring弄慰,根據(jù)不同的querystring返回不同的內(nèi)容第美。querystring改變的時候,對應(yīng)的內(nèi)容發(fā)生變化
(3)注意: url中的問號陆爽,使用英文格式的什往,不然獲取的url中有EF%BC%等,例:
問號格式錯誤
(4)測試:
image.png
-
querystring.parse
(1) 引入 querystring模塊:const querystring = require('querystring');
(2) 使用querystring.parse
能夠?qū)@取的a = 100慌闭,轉(zhuǎn)換為{a:100}的格式别威,例:
parse
(3)url的hash,如下驴剔,"#"號后面的部分省古,不能使用parse獲取,因為hash無法傳遞到服務(wù)端丧失。
-
結(jié)構(gòu)化與非結(jié)構(gòu)化 (簡單了解即可)
(1)結(jié)構(gòu)化的數(shù)據(jù)豺妓,易通過程序訪問和分析,比如:對象布讹、數(shù)組琳拭。
(2)非結(jié)構(gòu)話的,不易通過程序分析描验,比如:字符串
(3)所以一般建議白嘁,盡量使用結(jié)構(gòu)化數(shù)據(jù)
6、使用response返回數(shù)據(jù)
- 返回json格式數(shù)據(jù)
(1)設(shè)置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: '創(chuàng)建成功'
}
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格式數(shù)據(jù)(了解即可鲁沥,不使用)
(1)設(shè)置Content-type:text/html
(2)如下:
返回html格式
7、使用request返回數(shù)據(jù)
- 流:
-
下載時:
(1)source(服務(wù)端)耕魄,dest(前端/客服端)
水相當(dāng)于下載的數(shù)據(jù)黍析,水管,相當(dāng)于網(wǎng)絡(luò)
image.png
(2)服務(wù)端 res.end(...)屎开,自動以流的形式返回給瀏覽器阐枣,瀏覽器識別到流,會持續(xù)接收信息奄抽。接收完之后蔼两,會顯示或處理。(比如:視頻一段段的加載顯示)
- 上傳時:
(1)source前端逞度,dest服務(wù)端
水相當(dāng)于上傳的數(shù)據(jù)额划,水管,相當(dāng)于網(wǎng)絡(luò) - 識別“流”档泽,并輸出數(shù)據(jù):
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數(shù)據(jù)
// const result = {
// errno: 0,
// message: '創(chuàng)建成功'
// }
// res.writeHead(200, { "Content-type": 'appLication/json' })
// res.end(JSON.stringify(result))
// 服務(wù)端,如何去識別并接收"流"
let bodyStr = ''
req.on('data', chunk => {
// chunk :"流"的每一段數(shù)據(jù)
bodyStr += chunk.toString() // 每次流一段馆匿,將其累加抑胎,
})
// 服務(wù)端,如何知道"流"流完了渐北,完了之后阿逃,會執(zhí)行end方法。
req.on('end', () => {
console.log('bodyStr:', bodyStr)
res.end('接收完')
})
// const result = {
// errno: 0,
// message: '創(chuàng)建成功'
// }
// res.writeHead(200, { 'Content-type': 'appLication/json' })
// res.end(JSON.stringify(result))
}
// res.end('POST成功33')
}).listen(3000)