在node.js中,要使用 HTTP 服务器和客户端,必须使用http
模块
const http = require('http')
模拟接受get请求的服务器
const http = require('http')
const url = require('url')
let server = http.createServer(function (request, response) {
console.log('request.url:', request.url)
let { pathname, query } = url.parse(request.url, true)
console.log(pathname, query)
})
server.listen(8090)
其中可以使用url
模块中的url.parse()
将得到的请求地址进行解析,假如地址栏输入了
[http://localhost:8090/reg?user=moking&password=123456](http://localhost:8090/reg?user=moking&password=123456)
url.parse(request.url, true)的解析结构就为:/reg [Object: null prototype] { user: 'moking', password: '123456' }
模拟接受post数据请求的服务器
const http = require('http')
const querystring = require('querystring')
let server = http.createServer(function (req, res) {
let arr = []
req.on('data', buffer => {
arr.push(buffer)
})
req.on('end', () => {
let buffer = Buffer.concat(arr)
let post = querystring.parse(buffer.toString())
console.log(post)
})
})
server.listen(8090)
其中querystring
模块提供用于解析和格式化 URL 查询字符串的实用工具,可以将数据进行解析。querystring.parse()
与上面的url.parse()
类似。
模拟网页注册登入的服务器
const http = require('http')
const url = require('url')
const fs = require('fs')
const querystring = require('querystring')
let users = {}
http.createServer((req, res) => {
let path = '', get = {}, post = {}
if (req.method == 'GET') {
let { pathname, query } = url.parse(req.url, true)
path = pathname
get = query
complete()
} else if (req.method == 'POST') {
path = req.url
let arr = []
req.on('data', buffer => {
arr.push(buffer)
})
req.on('end', () => {
let buffer = Buffer.concat(arr)
post = querystring.parse(buffer.toString())
complete()
})
}
function complete() {
let { username, password } = get
if (path == '/reg') {
if (users[username]) {
res.write(JSON.stringify({ error: 1, msg: `此用户已存在` }))
res.end()
} else {
users[username] = password
res.write(JSON.stringify({ error: 0, msg: `` }))
res.end()
}
} else if (path == '/login') {
if (!users[username]) {
res.write(JSON.stringify({ error: 1, msg: `找不到此用户` }))
res.end()
} else if (users[username] != password) {
res.write(JSON.stringify({ error: 1, msg: `密码错误` }))
res.end()
} else {
res.write(JSON.stringify({ error: 0, msg: `` }))
res.end()
}
} else {
fs.readFile(`www${req.url}`, (err, buffer) => {
if (err) {
res.writeHeader(404)
res.write('Not Found')
res.end()
} else {
res.write(buffer)
res.end()
}
})
}
}
}).listen(8080)
测试网页
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<form action="http://localhost:8090/aaa" method="post">
用户:<input type="text" name="username" id="">
密码: <input type="password" name="password">
<button type="submit">提交</button>
</form>
</body>
</html>
网友评论