在很多场景中,我们的服务器都需要跟用户的浏览器打交道,如发送验证码、登录表单提交。请求服务器数据一般都使用GET请求,表单提交到服务器一般都使用POST请求。
一、获取GET请求
由于GET请求直接被嵌入在路径中,URL是完整的请求路径,包括了?后面的部分,因此你可以手动解析后面的内容作为GET请求的参数。
node.js 中url模块中的parse函数提供了这个功能。
const http = require("http")
const url = require("url")
const util = require("util")
// 创建服务器
http.createServer(function (req, res) {
// 输出相应头
res.writeHead(200, { "Content-Type": "text/plain" })
res.end(util.inspect(url.parse(req.url, true)))
}).listen(8888)
console.log("服务器已经启动。。。http://127.0.0.1:8888");[^解析]: util是node.js的常用工具模块。util.inspect()是一个将任意对象转换为字符串的方法,通常用于调试和错误输出。
二、获取POST请求
POST请求的内容全部的都在请求体中,http.ServerRequest并没有一个属性内容为请求体,原因是等待请求体传输可能是一件耗时的工作。
比如上传文件,而很多时候我们可能并不需要理会请求体的内容,恶意的POST请求会大大消耗服务器的资源,所以 node.js默认是不会解析请求体的,当你需要的时候,需要手动来做。
const http = require("http")
const querystring = require("querystring")
var postHTML =
`<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<form action="" method="post">
姓名: <input type="text" name="uname"><br>
班级: <input type="text" name="class"><br>
<input type="submit" >
</form>
</body>
</html>`;
http.createServer(function (req, res) {
var body = ''
req.on("data", function (turck) {
body += turck
})
req.on("end", function () {
body = querystring.parse(body)
res.writeHead(200, { "Content-Type": "text/html;charset=UTF-8" });
if (body.uname && body.class) {
// 获取提交操作,获取提交信息,并输出
res.write(`姓名${body.uname}`)
res.write('<br>')
res.write(`班级${body.class}`)
} else {
// 说明是第一次加载,需要显示表单
res.write(postHTML);
}
res.end()
})
}).listen(8881);
console.log("服务器已经启动。。。http://127.0.0.1:8881");版权声明:本文为m0_63716324原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。