1.web服务器初体验
npm全局安装nodemon可以使服务器保持热更新
2.创建服务器的方式
第一种方式
第二种方式
- 回调函数
3.request对象分析
三种常用的request属性
(1)url:
通过url传递的参数决定返回什么数据
简单情况:
localhost:8000/login
复杂情况:
localhost:8000/login?username=why&password=123
这样的url就不是很好使用上一个方法,因此引入const url = require(‘url’)模块
使用url.parse(req.url)可以得到
得到了url对象后,就可以使用属性pathname了
再继续对query属性进行解析
可以使用字符串分割方法,但有点麻烦
因此引入const qs = require(‘querystring’)模块进行解析
使用qs.parse(query)得到
(2)post
发送请求:
在postman中将请求方式改为post,在body中选取json文件格式,写入
{
“username”: “Kobe”,
“password”: “123”
}
解析请求:
从req.on()方法中拿到需要的数据再进行解析
(3)headers
4.response对象分析
(1)响应结果:
res.write()
res.end()
(2)状态码
设置状态码方式一:
res.statusCode =400;
设置状态码方式二:
res.writeHead(400)
(3)设置响应的header
方式一:
方式二:
5.http中发送网络请求
http发送get请求:
最后还要调用一下req.end()
6.文件上传
(1)文件上传错误示范
因为data中含有一些除图片信息外的其他信息