响应不同类型数据
- 文件结构
index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>首页</title> </head> <body> <h1>我是首页</h1> </body> </html>
login.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>登录</title> </head> <body> <h1>我是登录</h1> </body> </html>
app.js
// 1.导入http模块 const http = require("http"); // 导入quertString,将参数转换为对象,方便处理 const quertString = require("querystring"); const path = require("path"); const rootPath = path.join(__dirname, 'www'); const staticServer = require("./staticServer"); // 2.通过http模块创建服务对象 const server = http.createServer(); // 3.通过服务对象监听用户请求 server.on('request', (req, res) => { // 获取静态资源 staticServer.readFile(req, res, rootPath); // 1.获取请求类型 let method = req.method.toLowerCase(); // 2.获取请求路径 let url = req.url; let path = url.split("?")[0]; // 3.获取请求参数 let params = ''; if (method === "get") { // 4.处理get请求参数 params = url.split("?")[1]; params = quertString.parse(params); // 5.处理路由 if (path.startsWith('/login')) { // 返回的数据类型 res.writeHead(200, { // 纯文本类型 // "Content-Type": "text/plain;charset=utf-8" // json类型 'Content-Type': 'application/json;' }); //res.end("nhw"); res.end(JSON.stringify({ name: "nhw", age: "33" })); } else if (path.startsWith('/register')) { console.log('get处理注册请求', params); } } else if (method === 'post') { // 4.处理post请求参数 req.on("data", (chunk) => { // 每次只能拿到一部分数据 params += chunk; }); req.on("end", () => { // 这里才能拿到完整的数据 params = quertString.parse(params); // 5.处理路由 if (path.startsWith('/login')) { console.log('post处理登录请求', params); } else if (path.startsWith('/register')) { console.log('post处理注册请求', params); } }); } }).listen(3000);
staticServer.js
- mime.json是用于获取文件后缀名对应的type类型
const fs = require("fs"); const path = require("path"); const mime = require("./mime.json"); // /** // * 读取静态资源 // * @param {请求对象} req // * @param {响应对象} res // * @param {资源路径} rootPath // */ function readFile(req, res, rootPath) { // 1.获取静态资源地址 let fileName = req.url.split("?")[0]; let filePath = path.join(rootPath, fileName); // 2.判断静态资源是否存在 if (!fs.existsSync(filePath)) { return; } // 3.获取静态资源后缀名 let fileExt = path.extname(filePath); // 4.根据后缀名取出对应类型 let type = mime[fileExt]; // 5.对文本类型进行特殊处理 if (type.startsWith("text")) { type += ";charst=utf-8;" } // 6.告诉客户端返回的数据类型 res.writeHead(200, { "Content-Type": type }); // 7.加载静态资源并返回静态资源 fs.readFile(filePath, (err, content) => { if (err) { res.end("Server Error"); return; } res.end(content); }); } module.exports = { readFile };
- 终端执行:nodemon app.js
- 请求——浏览器输入:http://127.0.0.1:3000/login.html
- 响应——浏览器显示:{"name":"nhw","age":"33"}