使用http模块创建一个服务的样子
var http = require('http');
http.createServer(function (request, response) {
// 发送 HTTP 头部
// HTTP 状态值: 200 : OK
// 内容类型: text/plain
response.writeHead(200, {'Content-Type': 'text/plain'});
// 发送响应数据 "Hello World"
response.end('Hello World\n');
}).listen(8888);
// 终端打印如下信息
console.log('Server running at http://127.0.0.1:8888/');
app.js(主入口)
const http = require('http');
const app = require('./module/route');
const ejs = require('ejs');
http.createServer(app).listen(3000);
app.get('/', (req, res) => {
res.send('首页');
});
app.get('/login', (req, res) => {
// 这里使用了ejs
ejs.renderFile('./views/login.ejs', {}, (err, data) => {
if (err) {
console.log(err);
return;
}
res.send(data);
});
});
app.post('/doLogin', (req, res) => {
res.send(req.body);
});
module/route(封装核心)
const url = require('url');
// 封装 res.end()
const changeRes = (res) => {
res.send = (data) => {
res.writeHead(200, {
'Content-Type': 'text/html;charset=utf-8',
});
res.end(data);
};
};
const service = () => {
let G = {
_get: {},
_post: {}
};
let app = (req, res) => {
// 给res上挂一个send,实际上调用的是res.end()
changeRes(res);
let pathname = url.parse(req.url).pathname;
let method = req.method.toLowerCase();
if (G[`_${method}`][pathname]) {
if (method === 'get') {
G._get[pathname](req, res);
}
if (method === 'post') {
// 用来接受post的数据
let postData = '';
req.on('data', (chunk) => (postData += chunk));
req.on('end', () => {
// 挂在req.body上
req.body = postData;
G._post[pathname](req, res);
});
}
} else {
res.send('页面不存在');
}
};
app.get = (path, cb) => {
// 注册方法
G._get[path] = cb;
};
app.post = (path, cb) => {
G._post[path] = cb;
};
return app;
};
// 这里用 service函数 包一下,避免全局变量污染
module.exports = service();