第一天
了解nodejs
- npm nodejs软件包管理器
- npm i * --save-dev表示安装在开发依赖,正式环境上不会存在
- 在package.json里面 script里可以加自定义的代码
- commonjs和Es6模块化的区别
- commonjs,module.export导出模块,示例
module.exports = sum
- es6Module是静态的,只能在代码执行之前引入,commonjs可以(动态)
服务端概念
- resposne:后端返回给前端的数据, response body :后端返回给前端的数据。
- response Content-type:后端返回的数据类型 json
- 定义前端请求的url规则 - 路由
- 用request请求数据,response返回数据
- 理由包含请求方法(get/post/...),定义url规则,定义请求参数字段,定义响应格式.
- 服务端的职责:提供前端需要展示的数据
- 服务端可以通过response返回给后端内容: 状态码,conytent-type,body,通过resquest获取url methods body
- 数据库存储数据,选择nodejs的原因:适合前端学习,尽快掌握服务端的流程和套路,能快速做出项目。
认识req,res
- 使用http模块,启动http服务,创建一个最简单的服务
const http = require("http")
const server = http.createServer((req,res)=>{
console.log('发起请求了')
console.log(req.url)
res.end("hello world")
})
server.listen(3000)
console.log("监听了3000端口");
定义路由
- 通过request可以获得url和methods
- 创建路由验证
const http = require("http")
const server = http.createServer((req,res)=>{
const url = req.url
const method = req.method
console.log(url,method);
if (url === "/index"&& method ==="GET"){
res.end("yes")
}else {
res.end("404")
}
})
server.listen(3000)
console.log("监听了3000端口");
querystring
- 什么是querystring, url?后面都是querystring,就是url参数.
- url中hash,后端获取不到hash