⽹络请求,知道请求路径是什么,请求参数是什么,可以响应结果。
5.1 引⼊的模块
const http = require('http')
const url = require('url')
const util = require('util')
5.2 解析请求路径和请求参数
http.createServer((req, res)=>{
let method = req.method //值常见的有GET\POST
console.log('请求⽅法', method)
// 这⾥的第⼆个参数必须是true
let _url = url.parse(req.url, parseQueryString=true)
console.log('请求路径', _url.pathname)
console.log('请求参数是', _url.query.name, _url.query.age)
// res.end(util.inspect(_url))
}).listen(3000, console.log('服务器启动了'))
5.3 返回html页⾯
const http = require('http')
htmlcode1 = `
<form action="http://localhost:3000/asadfadsf" method="GET">
<input type="text" name="name" value="zhagnsan">
<input type="submit" value="提交">
</form>
`
http.createServer((req, res)=>{
// 必须指定响应头,浏览器才能解析html
res.writeHead(500, {'Content-Type':'text/html; charset=utf8'})
// 调⽤write或者end写应答
res.end(htmlcode1)
}).listen(3000)
6、POST请求
POST请求是Stream,基于事件的。
解析POST请求的数据,使⽤querystring模块中的parse⽅法。
const http = require('http')
const querystring = require('querystring')
let form_html = `
<form action="http://localhost:3000/save" method="post">
姓名:<input type="text" name="name" id=""><br>
年龄:<input type="text" name="age" id=""><br>
<button type="submit">
保存
</button>
</form>
`
http.createServer((req, res)=>{
let data = ''; //data保存post中的数据
req.on('data', chunk=>{
data+=chunk;
// console.log('到来的数据', chunk.toString())
})
req.on('end',()=>{
// 解析post数据
let _data = querystring.parse(data)
console.log('解析post数据', _data)
})
res.writeHead(200, {'Content-Type':'text/html; charset=utf8'})
res.end(form_html)
}).listen(3000, console.log('服务器启动了', ))
7、重定向
为了解决重复提交,使⽤重定向。
在应答中使⽤302状态码,指定新的访问地址
res.writeHead(302, {'Location':'http://localhost:3000/'})
下⾯是完整的代码
const http = require('http')
const querystring = require('querystring')
let form_html = `
<form action="http://localhost:3000/save" method="post">
姓名:<input type="text" name="name" id=""><br>
年龄:<input type="text" name="age" id=""><br>
<button type="submit">
保存
</button>
</form>
`
http.createServer((req, res)=>{
if('GET'==req.method){
res.writeHead(200, {'Content-Type':'text/html; charset=utf8'})
res.end(form_html)
}else if('POST'==req.method){
let data = ''; //data保存post中的数据
req.on('data', chunk=>{
data+=chunk;
// console.log('到来的数据', chunk.toString())
})
req.on('end',()=>{
// 解析post数据
let _data = querystring.parse(data)
console.log('解析post数据', _data)
res.writeHead(302, {'Location':'http://localhost:3000/'})
res.end()
return
})
}
}).listen(3000, console.log('服务器启动了', ))
8、读写json⽂件
// 把string转为json形式,把json形式转为string
//把json形式转为string
// console.log('输出字符串', typeof JSON.stringify({'name':'wuchao', 'age':23}))
// 把string转为json形式
// console.log('输出json格式', typeof JSON.parse('{"name":"wuchao","age":23}'))
const fs = require('fs')
// 读json⽂件
fs.readFile('data.json', (err, data)=>{
let jsondata = JSON.parse(data.toString())
console.log('输出⽂件中的内容', jsondata, jsondata.name, jsondata.age) })