第6章 HTTP模块
基本使用
创建web服务器
js
// 1.导入 http 模块
const http = require('http');
// 2.创建 web 服务器实例
const server = http.createServer();
// 3.为服务器实例绑定 request 事件,监听客户端的请求
server.on('request', (req, res) => {
console.log('Someone visit our web server');
});
// 4.启动服务器
server.listen(80, ()=> {
console.log('server running at http://127.0.0.1');
});
req 请求对象
req 请求对象用于访问与客户端相关的数据或属性
js
server.on('request',(req) => {
// req.url为访问的路径
// req.method为发送请求的方法
const url = req.url;
const method = req.method;
const str = `Your request url is ${url},and request method is ${method}`;
console.log(str);
});
res 响应对象
res 响应对象用于访问与服务器相关的数据或属性
js
server.on('request', (req, res) => {
const url = req.url;
const method = req.method;
const str = `Your request url is ${url},and request method is ${method}`;
console.log(str);
// 解决中文乱码:将响应头的 Content-Type 的值设置为 text/html;charset=utf-8
res.setHeader('Content-Type', 'text/html; charset=utf-8',)
// 通过 res.end 方法返回内容
// res.end(str);
res.end("你好")
});
简单封装
入口文件
js
// bin/www.js
const http = require('http');
const serverHandle = require('../app');
const PORT = 8000;
const server = http.createServer(serverHandle);
server.listen(PORT, () => {
console.log('Server is running in http://localhost:8080');
});
处理 query
js
const querystring = require('querystring');
const query = querystring.parse(url.split('?')[1]);
处理 body
js
let body = '';
req.on('data', chunk => {
body += chunk.toString();
})
req.on('end', () => {
resData.postData = JSON.parse(postData);
res.end(JSON.stringify(resData));
})
处理路由
js
const handleUserRouter = require('./src/router/user');
// 处理 user 路由
const userData = handleUserRouter(req, res);
if (userData) {
res.end(JSON.stringify(userData));
return;
}
处理 404
js
res.writeHead(404, { 'Content-type': 'text/plain' });
res.write('404 Not Found\n');
res.end();
Model
js
// src/model/resModel.js
class BaseModel {
constructor(data, message) {
if (typeof data === 'string') {
this.message = data;
data = null;
message = null;
}
if (data) {
this.data = data;
}
if (message) {
this.message = message;
}
}
}
class SuccessModel extends BaseModel {
constructor(data, message) {
super(data, message);
this.errno = 0;
}
}
class ErrorModel extends BaseModel {
constructor(data, message) {
super(data, message);
this.errno = -1;
}
}
module.exports = {
SuccessModel,
ErrorModel
};
Router
js
const { login } = require('../controller/user');
const { SuccessModel, ErrorModel } = require('../model/resModel');
const handleUserRouter = (req, res) => {
const { method } = req;
// 登录
if (method === 'POST' && req.path === '/api/user/login') {
const { username, password } = req.body;
const result = login(username, password);
return result.then((data) => {
if (data.username) {
return new SuccessModel();
} else {
return new ErrorModel('登录失败');
}
});
}
};
module.exports = handleUserRouter;
Controller
js
const { exec } = require('../db/mysql');
const login = (username, password) => {
const sql = `select username, realname from users where username=${username} and password=${password}`;
return exec(sql).then((rows) => rows[0] || {});
};
module.exports = { login };
预览: