1.nodejs基本概念
nodejs 是什么?
- nodejs 是基于 Chome V8 引擎 的 javascript 运行时
- nodejs 出现前,js 只能在浏览器
- nodejs 出现后,js 能运行任何安装ndejs的环境运行
commonjs和ES6 Module有何区别?
- 语法不同
- commonjs 动态引入(执行时)
- ES6 Module 静态引入(编译时)
- 附:commonjs require的三个级别
- nodejs 自带模块,如 require('http')
- npm 安装模块,如 require('lodash')
- 自定义模块,如 require('../utils.js')
nodejs和前端js的区别?
- 都使用ES 语法
- 前端js使用JS Web API
- nodejs 使用 node API
附:应用区别
- 前端js 用于 网页,在浏览器运行
- nodejs 可用于服务端,如开发 web servw
- nodejs 也可用于本机,如webpack等 工具
2.nodejs处理http
如何启动http服务
const http = require('http');
const serve = http.createServe((req, res) => {
console。log('收到http请求')
//req 获取客户端信息
//res 返回信息
res.end('hello world')
})
serve.listen(3000);
如何定义路由
- 两大要素:method + pathname
- 从 req 获取,method 和 url
- 从 url 获取 pathname
const http = require('http');
const serve = http.createServe((req, res) => {
//req 获取客户端信息
const method = req.method
const url = req.url
const pathname = url.split('?')[0]
//根据 method 和 pathname 定义路由
if(method === 'GET' && pathname = 'xxx'){
//res 返回信息
res.end('xxx 路由')
}
})
serve.listen(8000);
如何获取querystring
req.query = querystring.parse(url.split('?')[1]) //解析querystring
res.end(JSON.stringify(req.query)) //返回querystring
附加:结构化与非结构化
- 结构化数据,易于程序分析,如 对象 与数组
- 非结构化数据,反之 如 字符串
- 编程中的数据,尽量做到结构化
如何获取request body
//接收数据
let postData='';
req.on('data', chunk =>{
post += chunk.toString()
})
req.on('end',() => {
console.log(postData)
res.end('hello world')
})
回顾 stream 流
如何返回json格式
res.writeHead(200, {
"Content-type":"application/json"
})
res.end(
JSON.stringify(someObj)
)
session如何实现登录
- cookie 可实现登录校验
- cookie 不能泄露用户信息,所以有了session
- session 存储用户信息,cookie和session关联
3.nodejs 框架
框架的作用和价值
- 封装原生API,让开发简单
- 规范流程和格式,如 koa2的中间件
- 让开发专注于业务和功能
async/await执行顺序
- await 后面的相当于异步回调的内容
koa2如何处理路由
router.post('/create', async function(ctx, next){
const query = ctx.query
const reqBody = ctx.request.body
ctx.body = { errno:0}
})
描述koa2洋葱切模型
- 代码示例
服务端经典分层模型
4.Mongodb
DB Collection Document 分别什么意思
- DB 数据库 一个系统的数据集合,如:留言板项目
- collection 一类数据的集合,如:所有用户数据
- Document 文档 单个数据,如:一个用户数据
Mongoose的Schema和Model 是什么意思
- Schema数据规范,定义哪些属性,数据类型,是否必需
- Model 数据模型,提供规范的API操作Document
- Model依赖于Schema,对应一个cllection
是否使用 Mysql数据库
- 开放性问题:正在学习中。。。。
- 关系型数据库,设计数据表
- SQL语句执行