博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Node开发入门
阅读量:6992 次
发布时间:2019-06-27

本文共 2126 字,大约阅读时间需要 7 分钟。

本文涉及四个文件:

  • index.js                   调度和设置
  • requestHandlers   页面输出
  • server.js                  服务器启动
  • router.js                  路由逻辑

 

index.js

//index.js(设置路由并调用server启动服务器)var server = require("./server"),     router = require("./router"),     requestHandlers = require("./requestHandlers");var handle = {};handle["/"] = requestHandlers.start;handle["/start"] = requestHandlers.start;handle["/sb"] = requestHandlers.sb;server.start(router.route, handle);

requestHandlers.js

//requestHandlers.js(页面函数)var querystring = require("querystring");function start(response) {    var body = '' +        '' +        '
' + '' + '' + '
' + '
' + '
' + '
' + '' + ''; response.writeHead(200, { "Content-Type": "text/html" }); response.write(body); response.end();}function sb(response, postData) { response.writeHead(200, { "Content-Type": "text/plain" }); response.write(querystring.parse(postData).text); response.end();}exports.start = start;exports.sb = sb;

router.js

//router.js(路由逻辑)function route(handle, pathname, response, postData) {    console.log("来自" + pathname+"的请求");    if (typeof handle[pathname] === "function") {        handle[pathname](response, postData);    } else {        console.log("未发现来自" + pathname+"的请求");        response.writeHead(404, { "Content-Type": "text/plain" });        response.write("404 Not found");        response.end();    }};exports.route = route;

server.js

//server.js(服务器启动函数)var http = require("http"), url = require("url");function start(route, handle) {    function onRequest(request, response) {        var postData = "";        var pathname = url.parse(request.url).pathname;        console.log("来自" + pathname + "的请求已接收");        request.setEncoding("utf8");        request.addListener("data", function (postDataChunk) {            postData += postDataChunk;        });        request.addListener("end", function () {            route(handle, pathname, response, postData);        })    }    http.createServer(onRequest).listen(3000);    console.log("服务器已启动");}exports.start = start;

 

转载于:https://www.cnblogs.com/boystar/p/4742036.html

你可能感兴趣的文章
Gitlab omnibus 8.15.1 升级到 9.5.+
查看>>
PHP configure: error: mcrypt.h not found. Please reinstall libmcrypt.(转)
查看>>
awk命令——报告生成工具
查看>>
Linux开机启动流程描述
查看>>
“两只小熊队”Alpha版本展示博客
查看>>
创建django的不同环境
查看>>
Top 10 command-line commands for managing Windows 7 desktops
查看>>
CentOS5.4安装samba服务
查看>>
学习笔记之简单工厂设计模式
查看>>
Spring+SpringMVC+MyBatis+Maven框架整合
查看>>
MFC读写文件
查看>>
linux优化
查看>>
手动制作mini linux详细步骤—之一
查看>>
kali密码离线破解
查看>>
Bootstrap优秀模板-Unify.2.6.2
查看>>
适合新手了解的GUN/Linux起源
查看>>
怎么学习python?
查看>>
面向对象与面向过程的区别
查看>>
Python数据类型
查看>>
MySQL增删改查--之改
查看>>