热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

facebookstatusboxusingnode-jsexpressjsandmysql_MySQL

facebookstatusboxusingnode-jsexpressjsandmysql
NodeJS

byShahid Shaikh· June 29, 2014

fbstatusbox

I have already explained about Express.js tutorial and creating simple app with it. As promised in that post i thought to come up with another Express.js tutorial with MySQL. But again, explaining just the concept about library is not enough and this is not even whycodeforgeekexits. So i thought to come up with example and demo of real time frequent use thing which i can wrap around my tutorial and here it is – Facebook Status box using Node.js and MySQL.

Want to know about Express.js ?Read here.

If you want to view the demonstration of this app, you may see it in video down below. Since i do not have enough money to host Node.js demo online, i found YouTube best alternative to do that and of course you can download the source code for free from Github .

Directory Structure of Status Box:

direcotry strcuture

Directory structure of Status box app.

In main folder there are 3 directories named as “ js “, “ node_modules “, “ views “. Server logic is placed in main folder as Server.js and of course package.json.

node_modules is automatically created by NPM after installing it.

JS -> handleDB.js : This file contains code to perform MySql operations and we are importing it in Server.js.

views->index.html : Normal HTML file with some DOM elements.

Define package.json:

Package.json is a file which contains every information about your app like Name, version, author and above all dependencies which your app to run. Package.json file made deployment of Node.js app very quick and easy.

File: package.json

1

2

3

4

5

6

7

8

9

10

{

"name": "fbstatus-app",

"version": "1.0.0",

"dependencies":

{

"express": "~4.0.0",

"mysql":"*",

"ejs": "~1.0.0"

}

}

Installing dependencies of Facebook status box app:

I hope you have created any folder and placed package.json. Switch to that folder using command prompt using CD command and type:

npm install

That’s it. Wait for some time and let NPM install everything for you.

Server.js implementation:

Time to do some real stuff. Create file and name it as Server.js and put below code in it.

1

2

3

4

5

6

7

var express = require ( 'express' )

;

var url = require ( 'url' )

;

var db = require ( './js/handleDB' )

;

var app = express ( )

;

app. set ( 'views' , __dirname + '/views' )

;

app. set ( 'view engine' , 'ejs' )

;

app.engine('html', require('ejs') .renderFile)

;

From line 1 to line 3 we are simply importing libraries which we have installed in node_modules. in line 4 we are creating our express app. from line 4 to line 7 we are telling node to set “View” path (concept of MVC pattern) to folder named as “views”. Since we want to send HTML file in response to HTTP request we are going to need EJS to render HTML file and that’s what we did in line 6,7.

Implementing Router to handle HTTP Request:

To handle request such as “user want to see home page” or “user want to add status” we need router (which router request to particular function written to fulfill that request). So here is simple express.js router in Server.js file.

app.all(“*”,function(req,res){

//Code to handle router

});

You can use app.get or app.post for this as well but since i need to access different router and want to wrap it in single switch case i am using app.all(). Inside this function you can use URL variable and determine whether user request “homepage” from browser or user hit the DOM elements, all up to you. To handle Facebook status app router i am using following code.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

app. all ( '*' , function ( req , res )

{

var path = url. parse ( req. url ) . pathname

;

if ( path == "/"

)

{

//it means app is loaded with no additional URL parameter.

//e.g: http://localhost:3000 and on it we will return HTML page.

res. render ( "index.html" )

;

}

else if ( path == "/add" )

{

var status = url. parse ( req. url , true ) . query

;

//This line will get the textarea value written in HTML page (that value is status update)

db. add_status ( status , res )

;

//here we have called function to add status into DB.

}

})

;

Now to start our app and listen to request add these line in Server.js file and save it.

app.listen(3000);

Create View ( Just HTML page ):

Okay so let’s create front-end of our app. Oh yes we need one box on which user will type status and hit on “Add Status” button. We have to deal with click event in order to capture and send request to our Server.js to perform other functions. And when it’s about to handle events, jquery is always a Savior.

File : index.html ( Stored in Views folder )

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

Facebook Status Update using Node.JS and MySQL

HTML part is very easy and i don’t find any reason to explain it though. Javascript part is however different story. In click function we are hitting the URL with POST function and that URL is gonna be capture by Server and calls DB function.

Hey What about Database :D

Okay time to create back-end. No big deal i hope you have Phpmyadmin installed in your system. Just go there and create any database and inside create one table with three rows. I have given name to database as “fbstatus” and table as “ status “. inside “status” table i have created three rows ( status_id , s_text , t_status ) where ID is auto generated and text_t is of TEXT data type, t_status is time-stamp field.

Handle Database functions:

In Server.js file i have import handleDB which is stored in JS folder. Here is a code of handleDB.js. file name: HandleDB.js (stored in JS folder)

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

var db = require ( 'mysql' )

;

var cOnnection= db. createConnection (

{

host : "localhost"

,

user : "root"

,

password : ""

,

database :

"fbstatus"

} )

;

module. exports =

{

add_status : function ( s , res )

{

var query = "insert into status(s_text,t_status) values ('" + s. status + "',CURRENT_TIMESTAMP)"

;

connection. query ( query , function ( err , rows )

{

if ( err )

{

console. log ( "Connot execute" )

;

}

else

{

console. log ( "Status " + s. status + " is been added to Database" )

;

res. end ( "Yes" )

;

}

} )

;

}

}

;

If you have different mysql credentials than mine then just update it in code.

All done ! Let’s run.

Okay time to run the code. No big deal just switch to that folder which you have created (mine is “fb status update”) and type “node Server.js”. You may access your app at http://localhost:3000 via any web browser.

推荐阅读
  • 本文介绍了在开发Android新闻App时,搭建本地服务器的步骤。通过使用XAMPP软件,可以一键式搭建起开发环境,包括Apache、MySQL、PHP、PERL。在本地服务器上新建数据库和表,并设置相应的属性。最后,给出了创建new表的SQL语句。这个教程适合初学者参考。 ... [详细]
  • Java实战之电影在线观看系统的实现
    本文介绍了Java实战之电影在线观看系统的实现过程。首先对项目进行了简述,然后展示了系统的效果图。接着介绍了系统的核心代码,包括后台用户管理控制器、电影管理控制器和前台电影控制器。最后对项目的环境配置和使用的技术进行了说明,包括JSP、Spring、SpringMVC、MyBatis、html、css、JavaScript、JQuery、Ajax、layui和maven等。 ... [详细]
  • 在springmvc框架中,前台ajax调用方法,对图片批量下载,如何弹出提示保存位置选框?Controller方法 ... [详细]
  • 本文介绍了前端人员必须知道的三个问题,即前端都做哪些事、前端都需要哪些技术,以及前端的发展阶段。初级阶段包括HTML、CSS、JavaScript和jQuery的基础知识。进阶阶段涵盖了面向对象编程、响应式设计、Ajax、HTML5等新兴技术。高级阶段包括架构基础、模块化开发、预编译和前沿规范等内容。此外,还介绍了一些后端服务,如Node.js。 ... [详细]
  • MySQL中的MVVC多版本并发控制机制的应用及实现
    本文介绍了MySQL中MVCC的应用及实现机制。MVCC是一种提高并发性能的技术,通过对事务内读取的内存进行处理,避免写操作堵塞读操作的并发问题。与其他数据库系统的MVCC实现机制不尽相同,MySQL的MVCC是在undolog中实现的。通过undolog可以找回数据的历史版本,提供给用户读取或在回滚时覆盖数据页上的数据。MySQL的大多数事务型存储引擎都实现了MVCC,但各自的实现机制有所不同。 ... [详细]
  • 本文介绍了如何使用jQuery和AJAX来实现动态更新两个div的方法。通过调用PHP文件并返回JSON字符串,可以将不同的文本分别插入到两个div中,从而实现页面的动态更新。 ... [详细]
  • 从零基础到精通的前台学习路线
    随着互联网的发展,前台开发工程师成为市场上非常抢手的人才。本文介绍了从零基础到精通前台开发的学习路线,包括学习HTML、CSS、JavaScript等基础知识和常用工具的使用。通过循序渐进的学习,可以掌握前台开发的基本技能,并有能力找到一份月薪8000以上的工作。 ... [详细]
  • Allegro总结:1.防焊层(SolderMask):又称绿油层,PCB非布线层,用于制成丝网印板,将不需要焊接的地方涂上防焊剂.在防焊层上预留的焊盘大小要比实际的焊盘大一些,其差值一般 ... [详细]
  • 本文介绍了Redis的基础数据结构string的应用场景,并以面试的形式进行问答讲解,帮助读者更好地理解和应用Redis。同时,描述了一位面试者的心理状态和面试官的行为。 ... [详细]
  • SpringMVC接收请求参数的方式总结
    本文总结了在SpringMVC开发中处理控制器参数的各种方式,包括处理使用@RequestParam注解的参数、MultipartFile类型参数和Simple类型参数的RequestParamMethodArgumentResolver,处理@RequestBody注解的参数的RequestResponseBodyMethodProcessor,以及PathVariableMapMethodArgumentResol等子类。 ... [详细]
  • 在Android中解析Gson解析json数据是很方便快捷的,可以直接将json数据解析成java对象或者集合。使用Gson解析json成对象时,默认将json里对应字段的值解析到java对象里对应字段的属性里面。然而,当我们自己定义的java对象里的属性名与json里的字段名不一样时,我们可以使用@SerializedName注解来将对象里的属性跟json里字段对应值匹配起来。本文介绍了使用@SerializedName注解解析json数据的方法,并给出了具体的使用示例。 ... [详细]
  • 数据库锁的分类和应用
    本文介绍了数据库锁的分类和应用,包括并发控制中的读-读、写-写、读-写/写-读操作的问题,以及不同的锁类型和粒度分类。同时还介绍了死锁的产生和避免方法,并详细解释了MVCC的原理以及如何解决幻读的问题。最后,给出了一些使用数据库锁的实际场景和建议。 ... [详细]
  • ps:写的第一个,不足之处,欢迎拍砖---只是想用自己的方法一步步去实现一些框架看似高大上的小功能(比如说模型中的toArraytoJsonsetAtt ... [详细]
  • 前言:关于跨域CORS1.没有跨域时,ajax默认是带cookie的2.跨域时,两种解决方案:1)服务器端在filter中配置详情:http:blog.csdn.netwzl002 ... [详细]
  • React 小白初入门
    推荐学习:React官方文档:https:react.docschina.orgReact菜鸟教程:https:www.runoob.c ... [详细]
author-avatar
iflbicfb_6114756
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有