使用http模块创建一个服务的样子

    1. var http = require('http');
    2. http.createServer(function (request, response) {
    3. // 发送 HTTP 头部
    4. // HTTP 状态值: 200 : OK
    5. // 内容类型: text/plain
    6. response.writeHead(200, {'Content-Type': 'text/plain'});
    7. // 发送响应数据 "Hello World"
    8. response.end('Hello World\n');
    9. }).listen(8888);
    10. // 终端打印如下信息
    11. console.log('Server running at http://127.0.0.1:8888/');

    app.js(主入口)

    1. const http = require('http');
    2. const app = require('./module/route');
    3. const ejs = require('ejs');
    4. http.createServer(app).listen(3000);
    5. app.get('/', (req, res) => {
    6. res.send('首页');
    7. });
    8. app.get('/login', (req, res) => {
    9. // 这里使用了ejs
    10. ejs.renderFile('./views/login.ejs', {}, (err, data) => {
    11. if (err) {
    12. console.log(err);
    13. return;
    14. }
    15. res.send(data);
    16. });
    17. });
    18. app.post('/doLogin', (req, res) => {
    19. res.send(req.body);
    20. });

    module/route(封装核心)

    1. const url = require('url');
    2. // 封装 res.end()
    3. const changeRes = (res) => {
    4. res.send = (data) => {
    5. res.writeHead(200, {
    6. 'Content-Type': 'text/html;charset=utf-8',
    7. });
    8. res.end(data);
    9. };
    10. };
    11. const service = () => {
    12. let G = {
    13. _get: {},
    14. _post: {}
    15. };
    16. let app = (req, res) => {
    17. // 给res上挂一个send,实际上调用的是res.end()
    18. changeRes(res);
    19. let pathname = url.parse(req.url).pathname;
    20. let method = req.method.toLowerCase();
    21. if (G[`_${method}`][pathname]) {
    22. if (method === 'get') {
    23. G._get[pathname](req, res);
    24. }
    25. if (method === 'post') {
    26. // 用来接受post的数据
    27. let postData = '';
    28. req.on('data', (chunk) => (postData += chunk));
    29. req.on('end', () => {
    30. // 挂在req.body上
    31. req.body = postData;
    32. G._post[pathname](req, res);
    33. });
    34. }
    35. } else {
    36. res.send('页面不存在');
    37. }
    38. };
    39. app.get = (path, cb) => {
    40. // 注册方法
    41. G._get[path] = cb;
    42. };
    43. app.post = (path, cb) => {
    44. G._post[path] = cb;
    45. };
    46. return app;
    47. };
    48. // 这里用 service函数 包一下,避免全局变量污染
    49. module.exports = service();