Summary of basic usage of Node18.x
- 1. Node installation
- 2、Buffer
- 3. fs module
- 4. path module
- 5. HTTP protocol
- 5.1, fiddler Chinese and Chinese version
- 5.2. Composition of request message
- 5.3. Composition of response message
- 5.4. Create HTTP service
- 5.5. Obtain HTTP request message
- 5.6. Set HTTP response message
- 5.7. Basic loading process of web resources
- 5.8. Static resource service
- 5.9. Set resource type (mime type)
- 5.9. Set resource type (mime type)
- 5.10, GET and POST request scenarios
- 5.11. The difference between GET and POST requests
Supporting video: Shang Silicon Valley 2023 version Node.js zero-based video tutorial, nodejs novice to master
Supporting code: https://gitee.com/Augenstern-creator/kuang-study-nodejs
1. Node installation
- Official website: https://nodejs.org/en/
-
To download historical versions: https://nodejs.org/dist/
- After the download is complete, install it
next
. Be careful not to check the box below.
- Enter it in the command line window
node -v
. The following picture appears, indicating that the installation is successful.
- Configure Node in WebStrom
- Change the Taobao mirror source: NPM mirror_NPM download address_NPM installation tutorial-Alibaba open source mirror station (aliyun.com)
npm config set registry http://registry.npmmirror.com
Use the following command to check whether it is successful:
npm config get registry
2、Buffer
2.1. Concept
Buffer is an array-like object 对象
used to represent a fixed-length byte sequence. Buffer is essentially a section of memory space specifically used for processing.二进制数据
2.2. Features
- Buffer size is fixed and cannot be adjusted
- Buffer has good performance and can directly operate on computer memory.
- The size of each element is 1 byte (byte)
2.3. Use
2.3.1. Create Buffer
The main ways to create Buffers in Node.js are as follows:
Buffer.alloc
: alloc means allocate
//创建了一个长度为 10 字节的 Buffer,相当于申请了 10 字节的内存空间,每个字节的值为 0
let buffer1 = Buffer.alloc(10);
// <Buffer 00 00 00 00 00 00 00 00 00 00>
console.log(buffer1);
Buffer.allocUnsafe
//创建了一个长度为 10 字节的 Buffer,buffer 中可能存在旧的数据, 可能会影响执行结果,所以叫unsafe
let buffer2 = Buffer.allocUnsafe(10);
Buffer.from
// 通过字符串创建 Buffer
let buffer3 = Buffer.from('hello');
// <Buffer 68 65 6c 6c 6f> 是 hello 每个字符在 unicode 中对应的数字所对应的二进制
console.log(buffer3);
// 通过数组创建 Buffer(数组里面的每个数字都可以转为二进制存入Buffer中)
let buffer4 = Buffer.from([105, 108, 111, 118, 101, 121, 111, 117]);
console.log(buffer4);
2.3.2. Conversion of Buffer and String
We can use toString
the method to convert Buffer into string
// Buffer 与字符串的转化
let buffer1 = Buffer.from([105, 108, 111, 118, 101, 121, 111, 117]);
// iloveyou
console.log(buffer1.toString())
toString is converted according to utf-8 encoding by default.
2.3.3. Reading and writing of Buffer
Buffer can [ ]
process data directly through.
// Buffer 与字符串的转化
let buffer1 = Buffer.from([105, 108, 111, 118, 101, 121, 111, 117]);
// iloveyou
console.log(buffer1.toString())
// 读取
// 108
console.log(buffer1[1]);
// 修改
buffer1[1] = 97;
3. fs module
The full name of fs file system
is called fs, which is a built-in module文件系统
in Node.js that can operate the disk in the computer.
3.1. File writing
File writing is to save data to a file . We can use the following methods to achieve this effect.
method | illustrate |
---|---|
writeFile | Asynchronous writing |
writeFileSync | Synchronous writing |
appendFile/appendFileSync | append write |
createWriteStream | Streaming writing |
3.1.1. writeFile asynchronous writing
-
grammar:
fs.writeFile(file,data[,options],callback)
-
Parameter Description:
- file file name
- data data to be written
- options option settings (optional)
- callback write callback
-
return value:
undefined
// require 是 Node.js 环境中的'全局'变量,用来导入模块
const fs = require('fs');
// 文件如果不存在,会自动帮我们创建文件
fs.writeFile('./1.txt','秦晓林真帅',err => {
//如果写入失败,则回调函数调用时,会传入错误对象,如写入成功, err 就是 null
if(err){
// 如果 err 是一个错误对象
console.log('写入失败');
}else{
console.log('写入成功');
}
})
3.1.2. writeFileSync synchronous writing
- grammar:
fs.writeFileSync(file,data[,options])
- Parameter description: no callback parameter
- file file name
- data data to be written
- options option settings (optional)
// require 是 Node.js 环境中的'全局'变量,用来导入模块
const fs = require('fs');
// 文件如果不存在,会自动帮我们创建文件
fs.writeFileSync('./1.txt','秦晓林你真帅')
This operation in Node.js is completed by other threads, and there are two modes for processing the results.
- Synchronous processing of JS main threadwill waitThe execution results of other threads, and then continue to execute the code of the main thread,Less efficient
- Asynchronous processing of JS main threadwon't waitThe execution results of other threads, and then continue to execute the code of the main thread,Higher efficiency
3.1.3、appendFile/appendFileSync
The function of appendFile is to append content at the end of the file. The syntax of appendFile is exactly the same as that of writeFile.
-
grammar:
fs.appendFile(file,data[,options],callback)
fs.appendFileSync(file, data[, options])
-
Return value: Both are undefined
const fs = require('fs');
// 文件如果不存在,会自动帮我们创建文件
fs.appendFile('1.txt','帅帅帅帅帅',err => {
//如果追加失败,则回调函数调用时,会传入错误对象,如追加成功, err 就是 null
if(err){
// 如果 err 是一个错误对象
console.log('追加失败');
}else{
console.log('追加成功')
}
})
3.1.4, createWriteStream streaming writing
-
grammar:
fs.createWriteStream(path[, options])
-
Parameter Description:
- path file path
- options option configuration** (optional)**
-
return value:
Object
// 1.导入fs
const fs = require('fs');
// 2.创建写入流对象
let ws = fs.createWriteStream('11.txt');
// 3.write 写入数据
ws.write('hello world1 \r\n');
ws.write('hello world2 \r\n');
// 4.关闭流
ws.end;
- A program consumes resources when opening a file. Streaming writing can reduce the number of times the file is opened and closed.
- Streaming writing method is suitable forLarge file writing or frequent writingscenario, writeFile is suitable forWrite less frequentlyscene
3.2. File reading
File reading: Get data from the file in the following ways:
method | illustrate |
---|---|
readFile | Asynchronous reading |
readFileSync | Synchronous reading |
createReadStream | Streaming read |
3.2.1. readFile asynchronous reading
-
grammar:
fs.readFile(path[, options], callback)
-
Parameter Description:
- path file path
- options option configuration
- callback callback function
-
return value:
undefined
// 1.导入fs
const fs = require('fs');
// 2.异步读取
fs.readFile('1.txt',(err,data) => {
if(err){
console.log('err 是一个错误对象,读取失败');
}else{
console.log('读取成功');
// 打印读取到的文件内容
console.log(data);
// 读取到的内容是一个 Buffer, 我们可以转成字符串
console.log(data.toString());
}
})
3.2.2, readFileSync synchronous reading
- grammar:
fs.readFileSync(path[, options])
- Parameter Description:
- path file path
- options option configuration
- return value:
string | Buffer
// 同步读取
let data1 = fs.readFileSync('1.txt');
let data2 = fs.readFileSync('1.txt','utf-8');
console.log(data1)
3.2.3, createReadStream streaming reading
Streaming reading is to read one piece of the file at a time, and then read another piece after reading one piece. The readFile above reads the file into memory at one time.
-
grammar:
fs.createReadStream(path[, options])
-
Parameter Description:
- path file path
- options option configuration ( optional )
-
return value:
Object
// 1.导入fs
const fs = require('fs');
// 2.创建读取流对象
const rs = fs.createReadStream('1.txt');
// 3.每次取出 64kb 数据后执行一次 data 回调
rs.on('data', data => {
// 读取到的 data 是 Buffer 对象
console.log(data.toString());
console.log(data.length);
})
// 4.读取完毕后,执行end回调
rs.on('end',() => {
console.log('读取完成');
})
3.3. File moving and renaming
In Node.js, we can move or rename files or folders using rename
orrenameSync
-
grammar:
fs.rename(oldPath, newPath, callback)
fs.renameSync(oldPath, newPath)
-
Parameter Description:
- oldPath The current path of the file
- newPath file new path
- callback callback after operation
// 1.导入fs
const fs = require('fs');
// 2.将 1.txt 改为 11.txt
fs.rename = ('1.txt', '11.txt', err => {
if(err){
console.log('重命名失败');
}else{
console.log('重命名成功')
}
})
// 将 1.txt 改为 移动到 txt.1.txt
fs.rename = ('1.txt', '../txt/1.txt', err => {
if(err){
console.log('移动失败');
}else{
console.log('移动成功')
}
})
3.4. File deletion
In Node.js, we can delete files using unlink
orunlinkSync
-
grammar:
fs.unlink(path, callback)
fs.unlinkSync(path)
-
Parameter Description:
- path file path
- callback callback after operation
// 1.导入fs
const fs = require('fs');
fs.unlink('1.txt',err => {
if(err){
console.log('删除失败');
}else{
console.log('删除成功');
}
})
fs.unlinkSync('1.txt');
3.5. Folder operation
With the help of Node.js, we can create, read, delete and other operations on folders
method | illustrate |
---|---|
mkdir/mkdirSync | Create folder |
readdir/readdirSync | Read folder |
rmdir/rmdirSync | delete folder |
3.5.1. Create folder
In Node.js, we can create folders using mkdir
ormkdirSync
-
grammar:
fs.mkdir(path[, options], callback)
fs.mkdirSync(path[, options])
-
Parameter Description
- path folder path
- options option configuration ( optional )
- callback callback after operation
// 1.导入fs
const fs = require('fs');
// 创建html文件夹
fs.mkdir('html',err => {
if(err){
console.log('新建失败');
}else{
console.log('新建成功');
}
})
// 递归创建 a/b/c 文件夹,需要加配置: recursive - 递归
fs.mkdir('a/b/c',{
recursive: true},err => {
if(err){
console.log('新建失败');
}else{
console.log('新建成功');
}
})
3.5.2. readdir reads the folder
In Node.js, we can use readdir
or readdirSync
to read the folder
-
grammar:
fs.readdir(path[, options], callback)
fs.readdirSync(path[, options])
-
Parameter Description:
- path folder path
- options option configuration ( optional )
- callback callback after operation
// 1.导入fs
const fs = require('fs');
// 异步读取文件夹txt
fs.readdir('/txt',(err,data) => {
if(err){
console.log('读取失败');
}else{
console.log('读取成功');
}
})
// 同步读取
let data = fs.readdirSync('/txt');
console.log(data);
3.5.3. rmdir delete folder
In Node.js, we can use rmdir
or rmdirSync
to delete a folder
-
grammar:
fs.rmdir(path[, options], callback)
fs.rmdirSync(path[, options])
-
Parameter Description:
- path folder path
- options option configuration ( optional )
- callback callback after operation
// 删除文件夹
fs.rmdir('/txt',(err,data) => {
if(err){
console.log('删除失败');
}else{
console.log('删除成功');
}
})
// 递归删除文件夹
fs.rmdir('/a/b/c',{
recursive: true},(err,data) => {
if(err){
console.log('递归删除失败');
}else{
console.log('递归删除成功');
}
})
3.6. Check resource status
In Node.js, we can use stat
or statSync
to view resource details
-
grammar:
fs.stat(path[, options], callback)
fs.statSync(path[, options])
-
Parameter Description:
- path folder path
- options option configuration ( optional )
- callback callback after operation
// 1.导入fs
const fs = require('fs');
fs.stat('1.txt', (err,data) => {
if(err){
console.log('操作失败');
}else{
console.log('操作成功');
console.log(data);
}
})
Result value object structure:
Stats {
dev: 177919585,
mode: 33206,
nlink: 1,
uid: 0,
gid: 0,
rdev: 0,
blksize: 4096,
ino: 6473924464353945,
size: 48,
blocks: 0,
atimeMs: 1694011150653.459,
mtimeMs: 1694009369275.4377,
ctimeMs: 1694009369275.4377,
birthtimeMs: 1693991825175.2554,
atime: 2023-09-06T14:39:10.653Z,
mtime: 2023-09-06T14:09:29.275Z,
ctime: 2023-09-06T14:09:29.275Z,
birthtime: 2023-09-06T09:17:05.175Z
}
3.7. Relative path problem
relative path:
-
./座右铭.txt
Motto.txt in the current directory -
座右铭.txt
Equivalent to the above writing -
../座右铭.txt
Motto.txt in the directory one level above the current directory
Absolute path:
D:/Program Files
Absolute path under windows system/usr/bin
Absolute path under Linux system
3.8、____dirname
__dirname
Similar torequire
, they are all 'global' variables in the Node.js environment.__dirname
Saved当前文件所在目录的绝对路径
, you can use to__dirname
concatenate it with the file name to form an absolute path.
// E:\Code\WebStorm\KuangStudy_Nodejs\03_fs
console.log(__dirname);
let data = fs.readFileSync(__dirname + '/data.txt');
console.log(data);
When using the fs module, try to
__dirname
convert the path to an absolute path.
4. path module
The path module providesOperation pathFunctions, we will introduce the following several more commonly used APIs:
API | illustrate |
---|---|
path.resolve | Absolute paths for splicing specifications are commonly used |
path.sep | Get the path separator of the operating system |
path.parse | Parse the path and return the object |
path.basename | Get the base name of a path |
path.dirname | Get the directory name of the path |
path.extname | Get the extension of the path |
5. HTTP protocol
Hypertext Transfer Protocol is an application layer communication protocol based on TCP/IP. This protocol details the rules for communication between browsers and World Wide Web servers . The agreement mainly stipulates two aspects:
- Client: used to send data to the server, which can be called a request message
- Server: Returns data to the client, which can be called a response message
5.1, fiddler Chinese and Chinese version
Post the link: fiddler Chinese version and Chinese version (like and share with friends) - Zhihu (zhihu.com)
5.1.1, fiddler configuration
By default, fiddler can only capture HTTP protocol packets. We need to configure it so that it can capture HTTPS protocol packets.
- Click Tools - Options: Tools - Options
- HTTPS - Tick
-
Restart fiddler
-
Change All process to Web Browsers
- We visit Baidu in the browser
5.2. Composition of request message
The request message includes:
- request line
- Request header
- Request body
5.2.1. Request line
The request line includes: request method, URL, version number
- Request method
method | effect |
---|---|
GET | Mainly used to obtain data |
POST | Mainly used for adding new data |
PUT | Mainly used to update data |
DELETE | Mainly used to delete data |
- URL :
http://www.baidu.com:80/index.html?a=100&b=200#logo
- http protocol (https, ftp, ssh, etc.)
- www.baidu.com domain name
- port 80
- /index.html path
- a=100&b=200 query string
- #logo hash (anchor link)
5.2.2. Request header
Request header format:Top name: top value
Common request headers include:
Request header | explain |
---|---|
Host | CPU name |
Connection | Connection settings 1. keep-alive: keep the connection 2. close: close the connection |
Cache-Control | cache control max-age = 0: no cache |
User-Agent | User agent, client string identifier, the server can use this identifier to identify which client this request comes from, generally distinguishing between PC and mobile terminals |
Accept | Set the type of data the browser receives |
Accept-Encoding | Set receiving Yasuo method |
Accept-Language | Set the received language q=0.7 as the preference coefficient, with a full score of 1 |
Cookie |
5.2.3. Request body
The format of the request body content is very flexible:
- Can be empty: GET request
- It can also be a string or JSON.
例如:
- 字符串: name=林晓&price=400000
- JSON:{“name”:“林晓”, “price”: 2000}
5.3、响应报文的组成
响应报文包括:
- 响应行
- 响应头
- 响应体
5.3.1、响应行
HTTP/1.1 200 OK
- HTTP/1.1 : HTTP协议版本号
- 200:响应状态码
- OK:响应码描述
5.3.2、响应头
# 缓存控制 private 私有的,只允许客户端缓存数据
Cache-Control:private
# 连接设置
Connection: keep-alive
# 设置响应体的数据类型以及字符集,响应体为html,字符集
Content-Type:text/html;charset=utf-8
# 响应体的长度,单位为字节
Content-Length:
5.3.3、响应体
响应体内容的类型是非常灵活的,常见的类型有 HTML、CSS、JS、图片、JSON
5.4、创建HTTP服务
使用 nodejs 创建 HTTP 服务:
//1. 导入 http 模块
const http = require('http');
//2. 创建服务对象 create 创建 server 服务
// request 意为请求. 是对请求报文的封装对象, 浏览器将请求报文放入 request,通过 request 对象可以获得请求报文的数据
// response 意为响应. 是对响应报文的封装对象, 服务端为浏览器返回响应报文,通过 response 对象可以设置响应报文,
const server = http.createServer((request,response) => {
// 设置响应体并结束响应
response.end("Hello Http Server");
});
// 3. 监听端口, 启动服务
// 监听端口9000,第二个参数只有服务启动成功之后才会执行
server.listen(9000,() => {
console.log("服务已经启动, 端口 9000 监听中");
})
http.createServer 里的回调函数的执行时机: 当接收到 HTTP 请求的时候,就会执行
例如我们启动上述 http 服务,然后在浏览器请求:http://127.0.0.1:9000
5.4.1、注意事项
-
命令行
ctrl + c
停止服务 -
当服务启动后,更新代码必须重启服务才能生效
-
响应内容中文乱码的解决办法
const server = http.createServer((request,response) => { // 设置响应体并结束响应 response.end("您好"); // 解决乱码 response.setHeader('content-type','text/html;charset=utf-8'); });
-
端口被占用:
Error: listen EADDRINUSE: address already in use :::9000
- 关闭当前正在运行监听端口的服务 ( 使用较多)
- 如果端口被其他程序占用,可以使用资源监视器找到占用端口的程序,然后使用任务管理器关闭对应的程序
记住上方的PID 16412,然后打开任务管理器根据 PID 找到并右键结束任务。
HTTP 协议默认端口是 80 。HTTPS 协议的默认端口是 443, HTTP 服务开发常用端口有 3000,8080,8090,9000 等
5.4.2、浏览器查看HTTP报文
- 查看请求行与请求头
- 查看请求体
因为GET请求的请求体大多为空,所以这里模拟 POST 请求
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<!-- 发送给9000端口 -->
<form action="http://127.0.0.1:9000" method="post">
<input type="text" name="username">
<input type="text" name="password">
<input type="submit" value="提交">
</form>
</body>
</html>
- 查看URL查询字符串
同时若我们访问 http://127.0.0.1:9000/search?keyword=5&num=1
,也是可以查询到URL字符串的。
- 查看响应行和响应头
- 查看响应体
5.5、获取HTTP请求报文
想要获取请求的数据,需要通过 request
对象
含义 | 语法 | 重点掌握 |
---|---|---|
请求方法 | request.method | * |
请求版本 | request.httpVersion | |
请求路径 | request.url | * |
URL路径 | require(‘url’).parse(request.url).pathname | * |
URL查询字符串 | require(‘url’).parse(request.url, true).query | * |
请求头 | request.headers | * |
请求体 | request.on(‘data’, function(data){}) request.on(‘end’, function(){}); |
//1. 导入 http 模块
const http = require('http');
//2. 创建服务对象 create 创建 server 服务
const server = http.createServer((request,response) => {
// 解决乱码
response.setHeader('content-type','text/html;charset=utf-8');
// 获取请求的方法
console.log(request.method);
// 获取请求的url:只包含 url 中的路径与查询字符串
console.log(request.url);
// 获取 HTTP 协议的版本号
console.log(request.httpVersion);
// 获取 HTTP 的请求头
console.log(request.headers);
// 设置响应体并结束响应
response.end("您好");
});
// 3. 监听端口, 启动服务
// 监听端口9000,第二个参数只有服务启动成功之后才会执行
server.listen(9000,() => {
console.log("服务已经启动, 端口 9000 监听中");
})
注意事项:
request.url
只能获取路径以及查询字符串,无法获取 URL 中的域名以及协议的内容request.headers
将请求信息转化成一个对象,并将属性名都转化成了『小写』- 关于路径:如果访问网站的时候,只填写了 IP 地址或者是域名信息,此时请求的路径为
/
- 关于 favicon.ico:这个请求是属于浏览器自动发送的请求
我们现在探究一下请求体的内容如何解析出来:
- 方法一:不常用,了解
//1. 导入 http 模块
const http = require('http');
//2. 创建服务对象 create 创建 server 服务
const server = http.createServer((request,response) => {
// 声明一个变量
let body = '';
// 绑定事件(data事件是一点点把请求体的内容取出)
request.on('data', data =>{
// 把取出来的请求体存入body当中
body += data;
})
// 绑定end事件(end事件是当把请求体取完之后触发的事件)
request.on('end',() => {
console.log(body);
})
// 解决乱码
response.setHeader('content-type','text/html;charset=utf-8');
// 设置响应体并结束响应
response.end("您好");
});
// 3. 监听端口, 启动服务
// 监听端口9000,第二个参数只有服务启动成功之后才会执行
server.listen(9000,() => {
console.log("服务已经启动, 端口 9000 监听中");
})
这里要发 POST 请求才会有请求体,可以使用我们上方的 form 表单发送请求到 http://127.0.0.1:9000/
,点击提交后控制台会输出
-
方法二:这种方法比较常用
例如我们浏览器输入
127.0.0.1:9000/search?username=admin&password=123456
//导入 http 模块
const http = require('http');
//导入 url 模块
const url = require('url');
//创建服务对象 create 创建 server 服务
const server = http.createServer((request,response) => {
console.log("request.url",request.url);
// /username=admin&password=123456
// url.parse 对url进行解析,若第二个参数为true,则会将URL查询字符串转换为对象,这样方便操作
let res = url.parse(request.url,true);
console.log("res",res);
/**
* Url {
protocol: null,
slashes: null,
auth: null,
host: null,
port: null,
hostname: null,
hash: null,
search: '?username=admin&password=123456',
query: [Object: null prototype] { username: 'admin', password: '123456' },
pathname: '/search',
path: '/search?username=admin&password=123456',
href: '/search?username=admin&password=123456'
}
*/
// 获取URL路径
console.log("res.pathname",res.pathname); // /search
// 获取URL查询字符串
console.log(res.query.username); //admin
console.log(res.query.password); //123456
// 解决乱码
response.setHeader('content-type','text/html;charset=utf-8');
// 设置响应体并结束响应
response.end("您好");
});
// 监听端口9000,第二个参数只有服务启动成功之后才会执行
server.listen(9000,() => {
console.log("服务已经启动, 端口 9000 监听中");
})
- 方法三:新版Nodejs方法,需要重点掌握
访问路径为:127.0.0.1:9000/search?username=admin&password=123456
//导入 http 模块
const http = require('http');
//创建服务对象 create 创建 server 服务
const server = http.createServer((request,response) => {
// 实例化 URL 对象,这样的 url 是一个对象
let url = new URL(request.url,'http://127.0.0.1');
// 输出
console.log(url);
/**
* URL {
href: 'http://127.0.0.1/search?username=admin&password=123456',
origin: 'http://127.0.0.1',
protocol: 'http:',
username: '',
password: '',
host: '127.0.0.1',
hostname: '127.0.0.1',
port: '',
pathname: '/search',
search: '?username=admin&password=123456',
searchParams: URLSearchParams { 'username' => 'admin', 'password' => '123456' },
hash: ''
}
*/
// 因为 URL 是一个对象,这样取得路径就很方便
console.log(url.pathname); // /search
// 获得URL查询字符串
console.log(url.searchParams.get('username')); //admin
console.log(url.searchParams.get('password')); //123456
// 解决乱码
response.setHeader('content-type','text/html;charset=utf-8');
// 设置响应体并结束响应
response.end("您好");
});
// 监听端口9000,第二个参数只有服务启动成功之后才会执行
server.listen(9000,() => {
console.log("服务已经启动, 端口 9000 监听中"
5.6、设置HTTP响应报文
作用 | 语法 |
---|---|
设置响应状态码 | response.statusCode |
设置响应状态描述 | response.statusMessage ( 用的非常少) |
设置响应头信息 | response.setHeader(‘头名’, ‘头值’) |
设置响应体 | response.write(‘xx’) response.end(‘xxx’) |
//导入 http 模块
const http = require('http');
//创建服务对象 create 创建 server 服务
const server = http.createServer((request,response) => {
// 设置响应码
response.statusCode = 203;
// 设置响应状态的描述
response.statusMessage = '专属响应码';
// 设置响应头(解决乱码)
response.setHeader('content-type','text/html;charset=utf-8');
// 设置响应体
response.write('I');
response.write('LOVE');
response.write('YOU');
// 设置响应体并结束响应
response.end();
});
// 监听端口9000,第二个参数只有服务启动成功之后才会执行
server.listen(9000,() => {
console.log("服务已经启动, 端口 9000 监听中");
})
5.7、网页资源的基本加载过程
网页资源的加载都是循序渐进的,首先获取 HTML 的内容, 然后解析 HTML 在发送其他资源的请求,
5.8、静态资源服务
- 静态资源是指内容长时间不发生改变的资源,例如图片,视频,CSS 文件,JS文件,HTML文件,字体文件等
- 动态资源是指内容经常更新的资源,例如百度首页,网易首页,京东搜索列表页面等
5.8.1、网站根目录或静态资源目录
HTTP 服务在哪个文件夹中寻找静态资源,那个文件夹就是静态资源目录,也称之为网站根目录
5.8.2、网页中的URL
网页中的 URL 主要分为两大类:相对路径与绝对路径
- 绝对路径可靠性强,而且相对容易理解,在项目中运用较多
形式 | 特点 |
---|---|
http://atguigu.com/web | 直接向目标资源发送请求,容易理解。网站的外链会用到此形式 |
//atguigu.com/web | 与页面 URL 的协议拼接形成完整 URL 再发送请求。大型网站用的比较多 |
/web | 与页面 URL 的协议、主机名、端口拼接形成完整 URL 再发送请求。中小型网站(用的比较多) |
- 相对路径在发送请求时,需要与当前页面 URL 路径进行计算,得到完整 URL 后,再发送请求,学习阶段用的较多
例如当前网页 url 为 http://www.atguigu.com/course/h5.html
形式 | 最终的url |
---|---|
./css/app.css | http://www.atguigu.com/course/css/app.css |
js/app.js | http://www.atguigu.com/course/js/app.js |
…/img/logo.png | http://www.atguigu.com/img/logo.png |
…/…/mp4/show.mp4 | http://www.atguigu.com/mp4/show.mp4 |
解释第一个 ./css/app.css
,表示请求的 URL 为当前文件夹下的 ./css/app.css
,而当前文件夹为 course,所以最终的拼接结果为http://www.atguigu.com/course/css/app.css
5.9、设置资源类型(mime类型)
媒体类型)是一种标准,用来表示文档、文件或字节流的性质和格式。
// mime 类型结构: [type]/[subType]
text/html
text/css
image/jpeg
image/png
application/json
HTTP 服务可以设置响应头 Content-Type 来表明响应体的 MIME 类型,浏览器会根据该类型决定如何处理资源,下面是常见文件对应的 mime 类型
html: 'text/html',
css: 'text/css',
js: 'text/javascript',
png: 'image/png',
jpg: 'image/jpeg',
gif: 'image/gif',
mp4: 'video/mp4',
mp3: 'audio/mpeg',
json: 'application/json'
对于未知的资源类型,可以选择 application/octet-stream
类型,浏览器在遇到该类型的响应时,会对响应体内容进行独立存储,也就是我们常见的下载效果
om/course/js/app.js |
| …/img/logo.png | http://www.atguigu.com/img/logo.png |
| …/…/mp4/show.mp4 | http://www.atguigu.com/mp4/show.mp4 |
解释第一个 ./css/app.css
,表示请求的 URL 为当前文件夹下的 ./css/app.css
,而当前文件夹为 course,所以最终的拼接结果为http://www.atguigu.com/course/css/app.css
5.9、设置资源类型(mime类型)
媒体类型)是一种标准,用来表示文档、文件或字节流的性质和格式。
// mime 类型结构: [type]/[subType]
text/html
text/css
image/jpeg
image/png
application/json
HTTP 服务可以设置响应头 Content-Type 来表明响应体的 MIME 类型,浏览器会根据该类型决定如何处理资源,下面是常见文件对应的 mime 类型
html: 'text/html',
css: 'text/css',
js: 'text/javascript',
png: 'image/png',
jpg: 'image/jpeg',
gif: 'image/gif',
mp4: 'video/mp4',
mp3: 'audio/mpeg',
json: 'application/json'
对于未知的资源类型,可以选择 application/octet-stream
类型,浏览器在遇到该类型的响应时,会对响应体内容进行独立存储,也就是我们常见的下载效果
5.10、GET和POST请求场景
GET请求的情况:
- 在地址栏直接输入 url 访问
- 点击 a 链接
- link 标签引入 css
- script 标签引入 js
- img 标签引入图片
- form 标签中的 method 为 get (不区分大小写)
- ajax 中的 get 请求
POST请求的情况:
- form 标签中的 method 为 post(不区分大小写)
- ajax 中的 post请求
5.11、GET和POST请求的区别
GET 和 POST 是 HTTP 协议请求的两种方式。
- GET 主要用来获取数据,POST 主要用来提交数据
- GET request with parameters is to append the parameters to the URL, then enter the url in the address bar to access the website. It is a GET request. POST request with parameters is to put the parameters in the request body.
- POST requests are safer than GET because the parameters will be exposed in the address bar in the browser
- There is a size limit for GET requests, generally 2K, while there is no size limit for POST requests.