实现一个 http 服务器 客户端会发送请求 GET POST
要处理不同的请求体的类型
- 表单格式(formData
a=1&b=2
),可以直接通信不会出现跨域问题 - JSON (
"{"kaimo":"313"}"
) - 文件格式 (二进制)
const http = require("http");
const url = require("url");
const querystring = require("querystring");let server = http.createServer();server.on("request", (req, res) => {let { pathname } = url.parse(req.url);if (pathname === "/login" && req.method == "POST") {const arr = [];req.on("data", (chunk) => {arr.push(chunk);});req.on("end", () => {let result = Buffer.concat(arr).toString();if (req.headers["content-type"] === "application/x-www-form-urlencoded") {let obj = querystring.parse(result, "&", "=");console.log(obj);res.setHeader("Content-Type", "application/json");res.end(JSON.stringify(obj));}});}
});server.listen(3000);
启动服务
nodemon "66 # form 数据格式化.js"
然后后编写测试 form 数据提交
<!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>凯小默测试 form 数据格式提交</title>
</head><body><form action="http://localhost:3000/login" method="POST" enctype="application/x-www-form-urlencoded"><input type="text" name="username"><input type="text" name="password"><button type="submit">提交</button></form>
</body></html>
输入数据,点击提交
服务端数据
页面变成了数据