上一节学习了 form 数据的处理,这一节学习 Ajax 的方式提交数据
服务端的代码如下
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); // 1)配置跨域 // 配置跨域头允许任何网站访问 res.setHeader("Access-Control-Allow-Origin", "*"); // 允许携带header res.setHeader("Access-Control-Allow-Headers", "Content-Type,Authorization"); // 默认支持 get 和 post res.setHeader("Access-Control-Allow-Methods", "GET,POST"); // 遇到 OPTIONS 预检请求,直接成功即可 if (req.method === "OPTIONS") { res.statusCode = "200"; res.end(); } // 2)解析请求体 const arr = []; req.on("data", (chunk) => { arr.push(chunk); }); req.on("end", () => { let result = Buffer.concat(arr).toString(); console.log("result---->", result); let obj; if (req.headers["content-type"] === "application/x-www-form-urlencoded") { obj = querystring.parse(result, "&", "="); } else if (req.headers["content-type"] === "application/json") { obj = JSON.parse(result); } console.log("obj---->", obj); // 3)根据不同路径返回对应内容 if (pathname === "/login" && req.method == "POST") { res.setHeader("Content-Type", "application/json"); res.end("登录成功"); } if (pathname === "/regist" && req.method == "POST") { res.setHeader("Content-Type", "application/json"); res.end(JSON.stringify(obj)); } }); }); server.listen(3000);
页面请求逻辑如下
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>凯小默测试对象的处理</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> <hr /> <button id="btn">注册提交数据</button> <script> // 默认如果域名,端口号,协议不一致会有跨域问题 btn.addEventListener("click", () => { // ajax 4部曲 1.创建 xhr 对象 2.开启请求 3.发送请求 4.监听状态变化 const xhr = new XMLHttpRequest(); xhr.open("POST", "http://localhost:3000/regist", true); // 异步提交 xhr.setRequestHeader("Content-Type", "application/json"); // 浏览器自动将相应的结果转化为对象 xhr.responseType = "json"; xhr.send( JSON.stringify({ name: "kaimo", age: 313 }) ); // xhr.readyState == 4 && xhr.status == 200 xhr.onload = function () { console.log(xhr.response); }; }); </script> </body> </html>
启动服务,点击提交就能看到请求成功,也可以自己去掉跨域头试试
nodemon "67 # 对象的处理.js"