2.2-http和url模块
Create by fall on 06 May 2022 Recently revised in 13 Mar 2024
http
创建简单的服务器
首先需要引入 http 模块 const http = require('http');
const http = require('http');
var sever = http.createServer(function(req,res){
res.setHeader('Content-Type','text/plain;charset=utf-8');
res.write('hello world 第二个程序');
res.end()
}).listen(8080,function(){
console.log('服务器部署成功,端口号:8080')
})
http 模块中常用的对象
request 对象包含了用户请求报中所有内容,通过 request 对象和可获取所有用户提交过来的数据,一般在使用时会简写为
req
response
对象用来向用户想硬一些数据,当服务器要向客户端进行响应的时候必须使用 response 对象,简写为res
有了 request 对象和 response 对象,既可以获取用户提交的数据,也可以向用户响应数据
Request 对象
request对象的API:
在文档中是
http.IncomingMessage
request.headers
:请求报文头request.rawheaders
:请求报文头(原生请求报文头)request.httpVersion
:http协议的版本号request.method
:请求的方法(get、post、delete)request.url
:请求的路径
const http = require('http')
const port = 8081
http.createServer(function(req,res){
console.log(req.headers) // 打印请求报文头,报文头以对象的形式进行存储
console.log(req.rawheaders) // 打印请求报文头,打印出以数组的形式存储的字符串
console.log(req.httpVersion) // 打印HTTP协议的版本
console.log(req.method) // 返回请求的方法
console.log(req.url) // 打印请求的路径
res.end('that is all')
// 请求一般产生两次,一次是文件读取,另一次是favicon.ico
}).listen(port,function(){
console.log('http:localhost:'+port)
})
Response 对象
response对象的API:
文档中对应的是
http.ServerResponse
res.write(chunk[,encoding][,callback])
res.end()
每个方法都要添加,用于结束本次请求(该方法会告诉服务器,所有响应头和主题都已经被发送,服务器将其视为已完成)。res.setHeader()
设置响应报文头,如果不设置,系统会自动设置,如果设置的覆盖了系统的响应头,则以设置的为基准res.statusCode
设置对应的状态码res.statusMessage
设置对应的状态码的消息res.writeHead()
直接向客户端写入响应报文
const http = require('http')
http.createServer((req,res)=>{
// end 函数如果指定了 data ,相当于调用了 res.write(data,encoding)之后再调用res.end(callback)
res.statusCode = 404 // 放置在setHeader前面,用于返回响应状态码
res.statusMessage = 'Not Found' // 返回状态码对应的消息
res.setHeader('Content-Type','text/plain;charset=utf-8') // setHeader 必须放在 res.end()之前,否则不会生效且报错
// 此处的 writeHead 相当于 statusCode statusMessage steHeader 三个合起来写入,这三个功能其实是写入对应 setHeader 里面的值
// res.writeHead(404,'not found',{
// "Content-Type":"text/plain;charset=utf-8"
// })
res.write('hello you beach')
res.end()
}).listen(8082,function(){
console.log('http://localhost:8082')
})
setHeader
:可以设置不同响应报文头,对浏览器传达不同的信息或者指令。
res.setHeader('Location',"/")
对于服务器来说,每一个对于文件的请求都要设置相应的请求结果,如果不设置,直接会设置为请求失败,进入错误处理,导致系统崩溃。
URL
通过 URL 来查询和控制域名相关的。
URL 的构成
┌─────────────────────────────────────────────────────────────────────────────────────────────┐
│ href │
├────────┬──┬─────────────────────┬────────────────────────┬───────────────────────────┬──────┤
│protocol│ │ auth │ host │ path │ hash │
│ │ │ ├─────────────────┬──────┼──────────┬────────────────┤ │
│ │ │ │ hostname │ port │ pathname │ search │ │
│ │ │ │ │ │ ├─┬──────────────┤ │
│ │ │ │ │ │ │ │ query │ │
" https: // user : pass @ sub.example.com : 8080 /p/a/t/h ? query=string # hash "
│ │ │ │ │ hostname │ port │ │ │ │
│ │ │ │ ├─────────────────┴──────┤ │ │ │
│protocol│ │ username │ password │ host │ │ │ │
├────────┴──┼──────────┴──────────┼────────────────────────┤ │ │ │
│ origin │ │ origin │ pathname │ search │ hash │
├───────────┴─────────────────────┴────────────────────────┴──────────┴────────────────┴──────┤
│ href │
└─────────────────────────────────────────────────────────────────────────────────────────────┘
注:
URL
对象的所有属性都是在类的原型上实现为 getter 和 setter,而不是作为对象本身的数据属性。因此,与传统的urlObjects不同,在URL
对象的任何属性(例如delete myURL.protocol
,delete myURL.pathname
等)上使用delete
关键字没有任何效果,但仍返回true
。
使用
使用格式:new URL(input[, base])
const myURL = new URL('https://example.org');
myURL.pathname = '/a/b/c';
myURL.search = '?d=e';
myURL.hash = '#fgh';
console.log(myURL.href)
注:如果 URL中写入的是相对路径,就必须填入 base
new URL('/','http://localhost')
const url = require('url');
const http =require('http')
const port = 2525
http.createServer((req,res)=>{
if(req.url != '/favicon.ico'){
const result = new URL(req.url,'http://localhost')
// const myURL =
// new URL('https://user:pass@sub.example.com:8080/p/a/t/h?query=string#hash');
console.log(result)
}
res.writeHead(200,{
'content-type':'text/html;charset=UTF-8'
})
res.write('<h1>内容</h1>')
res.end()
}).listen(port, ()=>{
console.log("listen in http://localhost:"+port)
})
Color
可以用来替代 chalk
import {styleText} from 'node:util';
console.log(styleText('red', 'Danger, Danger, Will Robinson!'));
console.log(styleText('yellow', 'Nine Princes of Amber'));
console.log(styleText('green', 'All systems are nomimal.'));
console.log(styleText('bgRed', 'Error, error Will Robinson!'));
console.log(styleText('redBright', 'Error, error Will Robinson!'));
console.log(styleText('bold', styleText('red','Error, error Will Robinson!')));