1. ECMA & Node
1.1 ECMAScript
- 不能操作dom,不能监听click事件,不能发送ajax请求
- 不能处理http请求,不能操作文件
1.2 JS
- 使用ECMAScript语法规范,外加web api,缺一不可
- DOM操作,BOM操作,事件绑定,Ajax等
- 两者结合,即可完成浏览器端任何操作
1.3 Node
- 使用ECMAScript语法规范,外加node api,缺一不可
- 处理http,处理文件等
- 两者结合,即可完成server端任何操作
2. CommonJS
/*
** a.js
*/
function add(a, b) {
return a + b
}
function mul(a, b) {
return a * b
}
module.exports = {
add,
mul
}
/*
** b.js
*/
const { add, mul } = require('./a')
const sum = add(10, 20)
const result = mul(100, 200)
console.log(sum, result)
// 解构实际如下:
// const opts = require('./a')
// const add = opts.add
// const mul = opts.mul
/*
** node b.js
*/
// npm init -y
// npm i lodash --save
const _ = require('lodash')
const arr = _.concat([1, 2], 3)
3. http请求
3.1 http请求概述
- 客户端dns解析,建立tcp链接,发送http请求
- 通过域名解析到远程ip地址
- Remote Address: 180.101.49.12:443
- 443是https默认端口,http默认80端口,每个人地址大概率不同
- 然后tcp三次握手,然后发送http请求
- 服务端接收http请求,处理,并返回
- 发送 request,返回 response
- 客户端接收返回数据,处理数据,渲染页面,执行js
3.2 nodejs处理http请求
- GET请求和querystring
- post请求和postdata
- 路由即接口地址
const http = require('http')
const server = http.createServer((req, res) => {
res.end('hello world')
})
server.listen(8000);
// 然后浏览器访问 http://localhost:8000
3.3 node处理get请求
- get请求,即客户端要向服务端获取数据,如查询列表
- 通过querystring传递数据,如 a.html?a=100&b=200
- 浏览器直接访问,就发送get请求
const http = require('http')
const querystring = require('querystring')
const server = http.createServer((req, res) => {
console.log('method:', req.method); // GET
const url = req.url; // 获取请求的完整url
console.log('url: ', url)
req.query = querystring.parse(url.split('?')[1]); // 解析querystring
console.log('query: ', query)
res.end(JSON.stringfy(req.query)) // 返回结果
});
server.listen(8000);
// 访问 http://localhost:8000/api/blog/list?author=zhangsan&keyword=A
// 控制台显示:
// method: GET
// url: /api/blog/list?author=zhangsan&keyword=A
// query: [Object: null prototype] {author: 'zhangsan', keyword: 'A'}
// method: GET
// url: /favicon.ico
// query: [Object: null prototype] {}
// 浏览器显示:
// {'author': 'zhangsan', 'keyword': 'A'}
// 浏览器默认还要发送一个请求,请求左上角icon
3.4 node处理post请求
- post请求,即客户端向服务器传递数据
- 浏览器无法直接模拟,需要postman
const http = require('http');
const server = http.createServer((req, res) => {
if(req.method === 'POST') {
// 打印传递数据格式
console.log('content-type: ', req.headers['content-type']);
// 接收数据
let postData = '';
req.on('data', chunk => {
postData += chunk.toString();
});
req.on('end', () => {
console.log('postData: ', postData);
res.end('hello world'); // 在这里返回,因为是异步
})
}
});
server.listen(8000);
- 定义一个postData存放post请求中不断传入的数据,若干次触发on中的data,结束触发end,一直监听数据流传入
- chunk是一个二进制格式,需要tostring方法转换格式
3.5 处理路由
const http = require('http');
const server = http.createServer((req, res) => {
const url = req.url;
const path = url.split('?')[0];
res.end(path);
});
server.listen(8000);
3.6 综合示例
const http = require('http')
const querystring = require('querystring')
const server = http.createServer((req, res) => {
const method = req.method
const url = req.url
const path = url.split('?')[0]
const query = querystring.parse(url.split('?')[1])
// 设置返回格式为 JSON
res.setHeader('Content-type', 'application/json')
// 返回的数据
const resData = {
method,
url,
path,
query
}
// 返回
if (method === 'GET') {
res.end(
JSON.stringify(resData)
)
}
if (method === 'POST') {
let postData = ''
req.on('data', chunk => {
postData += chunk.toString()
})
req.on('end', () => {
resData.postData = postData
// 返回
res.end(
JSON.stringify(resData)
)
})
}
})
server.listen(8000)
console.log('OK')
4. 搭建开发环境
- npm init -y
- 使用 nodemon 监测文件变化,自动重启node
- 使用 cross-env 设置 process.env 中全局环境变量,兼容linux和windows
"scripts": {
"dev": "cross-env NODE_ENV=dev nodemon ./bin/www.js",
"prd": "cross-env NODE_ENV=production nodemon ./bin/www.js"
},
"devDependencies": {
"cross-env": "^7.0.2",
"nodemon": "^2.0.4"
}
/*
** app.js
*/
const serverHandle = (req, res) => {
// 设置返回格式为json
res.setHeader('Content-type', 'application/json');
const resData = {
name: 'Ivan',
site: 'SH',
// process是node提供的全局变量,根据yarn run dev or prd 识别cross-env设置不同设置环境
env: process.env.NODE_ENV
}
res.end(JSON.stringify(resData));
};
module.exports = serverHandle;