资讯专栏INFORMATION COLUMN

不使用框架创建简单的Node.js web应用

LeanCloud / 2292人阅读

摘要:不使用框架创建简单的应用需求创建一个可以上传图片的应用。自定义模块刚才我们定义了一个简单的服务。处理数据存储本地安装服务安装客户端使用命令行新建文件修改待续如何使用创建一个代理服务器的适用场景

不使用框架创建简单的Node.js web应用

</>复制代码

  1. 需求: 创建一个可以上传图片的web应用。用户可以浏览应用,有一个文件上传的表单。选择图片上传,上传完成之后可以预览图片。上传的图片信息需要入库(mysql)。
一个简单的http服务

</>复制代码

  1. const http = require("http");
  2. // 创建一个服务
  3. const server = http.createServer((req, res) => {
  4. res.writeHead(200, { "Content-Type": "text/plain" });
  5. res.end("Hello World");
  6. });
  7. // 服务错误监听
  8. server.on("clientError", (err, socket) => {
  9. socket.end("HTTP/1.1 400 Bad Request
  10. ");
  11. });
  12. // 当前服务监听的端口
  13. server.listen(8888);
  14. console.log("Server has started.");

涉及到的api:
http.createServer
res.writeHead
res.end

当我们在编写node服务的时候,如果服务器有异常,那node服务就直接挂掉了。那如何保证我们的node服务不会关闭,并且会自动重启呢?
或者是我们修改了代码,如何实现修改的代码直接生效而不用重新手动重启node服务呢?

</>复制代码

  1. npm install -g nodemon

在生产环境我一般使用pm2来管理node服务。

自定义模块

刚才我们定义了一个简单的http服务。其中http是一个内置的模块。那其实我们的服务都会有一个入口文件,在这里我们定义为index.js。那我们如何像引用http内置模块一样,在index.js里使用server.js呢?

</>复制代码

  1. exportsmodule.exports 的区别:
    exportsmodule.exports的简写。如果修改了exports的引用,也就是重新给exports赋值,则exports只是在当前文件级作用域内可用,并且exports的修改不会影响到module.exports的值。

server.js

</>复制代码

  1. const http = require("http");
  2. function start() {
  3. const server = http.createServer((req, res) => {
  4. res.writeHead(200, { "Content-Type": "text/plain" });
  5. res.end("Hello World");
  6. });
  7. server.on("clientError", (err, socket) => {
  8. socket.end("HTTP/1.1 400 Bad Request
  9. ");
  10. });
  11. server.listen(8888);
  12. console.log("Server has started.");
  13. }
  14. // 通过给exports添加【属性值】的方式导出方法
  15. // 或者通过给module.exports添加属性值
  16. exports.start = start;

index.js

</>复制代码

  1. const server = require("./server");
  2. server.start();

</>复制代码

  1. node index.js
路由处理

我们知道,访问一个web网站会有不同的页面或者会调用不同的接口,那这些就对应这不同的请求路径,同时这些请求还会对应不同的请求方法(GET, POST等)。那node如何针对这些不同的请求路径去匹配对应的处理函数呢?

为了处理http请求的参数,我们需要获取到http请求的request,从中获取到请求方式以及请求路径。在这里会依赖 url内置模块。
首先建立routes文件夹存放路由处理

routes/index.js

</>复制代码

  1. module.exports = (req, res) => {
  2. res.writeHead(200, { "Content-Type": "text/plain" });
  3. res.end("Hello World");
  4. }

routes/upload.js

</>复制代码

  1. module.exports = (req, res) => {
  2. res.writeHead(200, { "Content-Type": "text/plain" });
  3. res.end("upload file");
  4. }

新建route.js文件处理路由

</>复制代码

  1. function route(handle, pathname, req, res) {
  2. if (typeof handle[pathname] === "function") {
  3. handle[pathname](req, res);
  4. } else {
  5. console.log("No request handler found for " + pathname);
  6. res.end("404 Not found");
  7. }
  8. }
  9. exports.route = route;

修改server.js

</>复制代码

  1. const http = require("http");
  2. const url = require("url");
  3. const routes = {};
  4. function use(path, routeHandler) {
  5. routes[path] = routeHandler;
  6. }
  7. function start(route) {
  8. function handleRequest(req, res) {
  9. const pathname = url.parse(req.url).pathname;
  10. route(routes, pathname, req, res)
  11. }
  12. const server = http.createServer(handleRequest);
  13. server.on("clientError", (err, socket) => {
  14. socket.end("HTTP/1.1 400 Bad Request
  15. ");
  16. });
  17. server.listen(8888);
  18. console.log("Server has started.");
  19. }
  20. module.exports = {
  21. start,
  22. use
  23. };

修改index.js

</>复制代码

  1. const server = require("./server");
  2. const index = require("./routes/index");
  3. const upload = require("./routes/upload");
  4. const router = require("./route");
  5. server.use("/", index);
  6. server.use("/upload", upload);
  7. server.start(router.route);
处理POST请求

我们显示一个文本区(textarea)供用户输入内容,然后通过POST请求提交给服务器。最后,服务器接受到请求,通过处理程序将输入的内容展示到浏览器中。

给request注册监听事件

</>复制代码

  1. request.addListener("data", function(chunk) {
  2. // called when a new chunk of data was received
  3. });
  4. request.addListener("end", function() {
  5. // called when all chunks of data have been received
  6. });

querystring登场,解析上传数据

修改server.js里的handleRequest方法

</>复制代码

  1. function handleRequest(req, res) {
  2. const pathname = url.parse(req.url).pathname;
  3. let postData = "";
  4. // 设置编码
  5. req.setEncoding("utf8");
  6. req.addListener("data", function(postDataChunk) {
  7. postData += postDataChunk;
  8. console.log("Received POST data chunk ""+
  9. postDataChunk + "".");
  10. });
  11. req.addListener("end", function() {
  12. route(routes, pathname, req, res, postData);
  13. });
  14. }

route.js多加一个参数postData

</>复制代码

  1. function route(handle, pathname, req, res, postData) {
  2. if (typeof handle[pathname] === "function") {
  3. handle[pathname](req, res, postData);
  4. } else {
  5. console.log("No request handler found for " + pathname);
  6. res.end("404 Not found");
  7. }
  8. }
  9. exports.route = route;

index.js

</>复制代码

  1. const exec = require("child_process").exec;
  2. module.exports = (req, res, postData) => {
  3. // 可以使用node模板
  4. const body = ""+
  5. ""+
  6. ""+
  7. ""+
  8. ""+
  9. "
    "+
  10. ""+
  11. ""+
  12. ""+
  13. ""+
  14. "";
  15. res.end(body);
  16. }

upload.js 修改

</>复制代码

  1. const querystring = require("querystring");
  2. module.exports = (req, res, postData) => {
  3. const content = querystring.parse(postData).text;
  4. res.writeHead(200, { "Content-Type": "text/plain; charset=utf-8"});
  5. res.end(content || "Empty");
  6. }
处理文件上传

</>复制代码

  1. npm install formidable

server.js修改

</>复制代码

  1. function handleRequest(req, res) {
  2. const pathname = url.parse(req.url).pathname;
  3. route(routes, pathname, req, res);
  4. }

routes/index.js

</>复制代码

  1. const exec = require("child_process").exec;
  2. module.exports = (req, res) => {
  3. // 可以使用node模板
  4. const body = ""+
  5. ""+
  6. ""+
  7. ""+
  8. ""+
  9. "
    "+
  10. ""+
  11. ""+
  12. ""+
  13. ""+
  14. "";
  15. res.writeHead(200, {"Content-Type": "text/html; charset=utf-8"});
  16. res.end(body);
  17. }

showFile.js获取磁盘图片信息

</>复制代码

  1. const fs = require("fs");
  2. const path = require("path");
  3. function show(req, res) {
  4. const rootPath = path.resolve();
  5. fs.readFile(`${rootPath}/tmp/test.png`, "binary", function(error, file) {
  6. if(error) {
  7. res.writeHead(500, {"Content-Type": "text/plain"});
  8. res.write(error + "
  9. ");
  10. res.end();
  11. } else {
  12. res.writeHead(200, {"Content-Type": "image/png"});
  13. res.write(file, "binary");
  14. res.end();
  15. }
  16. });
  17. }
  18. module.exports = show;

routes/uoload.js

</>复制代码

  1. const fs = require("fs");
  2. const formidable = require("formidable");
  3. const path = require("path");
  4. module.exports = (req, res) => {
  5. const form = new formidable.IncomingForm();
  6. const rootPath = path.resolve();
  7. form.parse(req, function(error, fields, files) {
  8. console.log("parsing done");
  9. fs.renameSync(files.upload.path, `${rootPath}/tmp/test.png`);
  10. res.writeHead(200, {"Content-Type": "text/html; charset=utf-8"});
  11. res.write("received image:
    ");
  12. res.write("");
  13. res.end();
  14. });
  15. }

同时在index.js中添加相应的路由。

处理数据存储

本地安装mysql服务
安装mysql客户端/使用命令行

</>复制代码

  1. npm install mysql

</>复制代码

  1. CREATE SCHEMA `nodestart` ;
  2. CREATE TABLE `nodestart`.`file` (
  3. `id` INT NOT NULL AUTO_INCREMENT,
  4. `filename` VARCHAR(300) NULL,
  5. `path` VARCHAR(500) NULL,
  6. `size` VARCHAR(45) NULL,
  7. `type` VARCHAR(45) NULL,
  8. `uploadtime` VARCHAR(45) NULL,
  9. PRIMARY KEY (`id`));

新建db.js文件

</>复制代码

  1. const mysql = require("mysql");
  2. const connection = mysql.createConnection({
  3. host : "localhost",
  4. user : "root",
  5. password : "123456",
  6. database : "nodestart"
  7. });
  8. function query(sql, params) {
  9. return new Promise((resolve, reject) => {
  10. connection.connect();
  11. connection.query(sql, params, function (error, results, fields) {
  12. if (error) reject(error);
  13. console.log("The solution is: ", results);
  14. resolve(fields);
  15. });
  16. connection.end();
  17. });
  18. }
  19. exports.query = query;

修改routes/upload.js

</>复制代码

  1. const fs = require("fs");
  2. const formidable = require("formidable");
  3. const path = require("path");
  4. const db = require("../db");
  5. module.exports = (req, res) => {
  6. const form = new formidable.IncomingForm();
  7. const rootPath = path.resolve();
  8. form.parse(req, function(error, fields, files) {
  9. console.log("parsing done");
  10. fs.renameSync(files.upload.path, `${rootPath}/tmp/test.png`);
  11. const fileObj = {
  12. size: files.upload.size,
  13. path: `${rootPath}/tmp/test.png`,
  14. filename: files.upload.name,
  15. type: files.upload.type,
  16. uploadtime: Date.now()
  17. }
  18. db.query("insert into nodestart.file set ?", fileObj).then((res) => {
  19. console.log(res)
  20. }).catch((err) => {
  21. console.log(err);
  22. })
  23. res.writeHead(200, {"Content-Type": "text/html; charset=utf-8"});
  24. res.write("received image:
    ");
  25. res.write("");
  26. res.end();
  27. });
  28. }

待续:

如何使用Node创建一个代理服务器 Node 的适用场景

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/105738.html

相关文章

  • (译 & 转载) 2016 JavaScript 后起之秀

    摘要:在年成为最大赢家,赢得了实现的风暴之战。和他的竞争者位列第二没有前端开发者可以忽视和它的生态系统。他的杀手级特性是探测功能,通过检查任何用户的功能,以直观的方式让开发人员检查所有端点。 2016 JavaScript 后起之秀 本文转载自:众成翻译译者:zxhycxq链接:http://www.zcfy.cc/article/2410原文:https://risingstars2016...

    darry 评论0 收藏0
  • 2016-JavaScript之星

    摘要:在,是当之无愧的王者,赢得了与之间的战争,攻陷了的城池。于月发布了版本,这一版本为了更好的表现加入了渲染方式。前端框架这个前端框架清单可能是年疲劳的元凶之一。的创建者,目前在工作为寻找构建简单性和自主配置性之间的平衡做了很大的贡献。 春节后的第一篇就从这个开始吧~本文已在前端早读课公众号上首发 原文链接 JavasScript社区在创新的道路上开足了马力,曾经流行过的也许一个月之后就过...

    Binguner 评论0 收藏0
  • 2019,开发者应该学习16个JavaScript框架

    摘要:它不仅从前端移动到后端,我们也开始看到它用于机器学习和增强现实,简称。由于其高使用率,年的现状调查将其称为采用的安全技术。机器学习框架在年的开发者峰会上,宣布了他们的机器学习框架的实现,称为。更高级别的用于在之上构建机器学习模型。 2019,开发者应该学习的16个JavaScript框架 showImg(https://segmentfault.com/img/remote/14600...

    Harpsichord1207 评论0 收藏0
  • javascript功能插件大集合 前端常用插件 js常用插件

    摘要:转载来源包管理器管理着库,并提供读取和打包它们的工具。能构建更好应用的客户端包管理器。一个整合和的最佳思想,使开发者能快速方便地组织和编写前端代码的下一代包管理器。很棒的组件集合。隐秘地使用和用户数据。 转载来源:https://github.com/jobbole/aw... 包管理器管理着 javascript 库,并提供读取和打包它们的工具。•npm – npm 是 javasc...

    netmou 评论0 收藏0
  • javascript功能插件大集合 前端常用插件 js常用插件

    摘要:转载来源包管理器管理着库,并提供读取和打包它们的工具。能构建更好应用的客户端包管理器。一个整合和的最佳思想,使开发者能快速方便地组织和编写前端代码的下一代包管理器。很棒的组件集合。隐秘地使用和用户数据。 转载来源:https://github.com/jobbole/aw... 包管理器管理着 javascript 库,并提供读取和打包它们的工具。•npm – npm 是 javasc...

    Hydrogen 评论0 收藏0
  • javascript功能插件大集合,写前端亲们记得收藏

    摘要:一个专注于浏览器端和兼容的包管理器。一个整合和的最佳思想,使开发者能快速方便地组织和编写前端代码的下一代包管理器。完全插件化的工具,能在中识别和记录模式。健壮的优雅且功能丰富的模板引擎。完整的经过充分测试和记录数据结构的库。 【导读】:GitHub 上有一个 Awesome – XXX 系列的资源整理。awesome-javascript 是 sorrycc 发起维护的 JS 资源列表...

    cfanr 评论0 收藏0

发表评论

0条评论

LeanCloud

|高级讲师

TA的文章

阅读更多
最新活动
阅读需要支付1元查看
<