66 # form data formatting

Implement an http server client that sends requests GET POST

To handle different request body types

  1. Form format (formData a=1&b=2), can communicate directly without cross-domain problems
  2. JSON ("{"kaimo":"313"}"
  3. file format (binary)
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);

start service

nodemon "66 # form 数据格式化.js"

Then write the test form data submission

<!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>

Enter data, click submit

insert image description here
server data

insert image description here

page becomes data
insert image description here

Guess you like

Origin blog.csdn.net/kaimo313/article/details/132179173