http://www.nodewiz.biz/nodejs-rest-api-with-mysql-and-express/

NPM Modules

  • Express
  • felixge/node-mysql - Source

Most articles about building a REST API for NodeJS will be based on MongoDB, I'm going to show you how to do it with MySQL.

Implementing the REST API

To implement all the routes required by the API, the full REST API for the node application will be a single file server.js which consists of the following methods:

Verb URI Action
GET /tableName Retrieve all wines
GET /tableName/id Retrieve the wine with the specified _id
POST /tableName Add a new wine
PUT /tableName/id Update wine with the specified _id
DELETE /tableName/id Delete the wine with the specified _id

Structure

Require your modules and create a http server based on express framework.

  1. var express = require('express'),
  2. app = express(),
  3. mysql = require('mysql');
  4. app.listen(3000);
  5. console.log('Rest Demo Listening on port 3000');

DB Connection

Setup your database and create a pool of connections to MySQL server;

  1. var express = require('express'),
  2. app = express(),
  3. mysql = require('mysql'),
  4. connectionpool = mysql.createPool({
  5. host : 'localhost',
  6. user : 'root',
  7. password : 'secret',
  8. database : 'rest_demo'
  9. });
  10. app.listen(3000);
  11. console.log('Rest Demo Listening on port 3000');

Where the configuration uses your host, username, password, and database name of course.

Routes

Your application will only need five REST routes to cover the methods table above.

  1. var express = require('express'),
  2. app = express(),
  3. mysql = require('mysql'),
  4. connectionpool = mysql.createPool({
  5. host : 'localhost',
  6. user : 'root',
  7. password : 'secret',
  8. database : 'rest_demo'
  9. }),
  10. res.setHeader({ 'Content-Type': 'application/json' });
  11. app.get('/:table', function(req,res){});
  12. app.get('/:table/:id', function(req,res){});
  13. app.post('/:table', function(req,res){});
  14. app.put('/:table/:id', function(req,res){});
  15. app.delete('/:table/:id', function(req,res){});
  16. app.listen(3000);
  17. console.log('Rest Demo Listening on port 3000');

Each route takes a callback function with request and response objects.

You may also notice we are going to be sending json Content-Type as a response always. I will set it up so that even errors will be responding in json, this is personal preference and you might want to do something else but i see it with AWS, Google, Facebook, ect so figured its generally a good idea.

Connection and Error Handling

We will be getting a connection from our pool, which may have reached its allocated limit and throw an error which needs to be handled.

  1. var express = require('express'),
  2. app = express(),
  3. mysql = require('mysql'),
  4. connectionpool = mysql.createPool({
  5. host : 'localhost',
  6. user : 'root',
  7. password : 'secret',
  8. database : 'rest_demo'
  9. });
  10. res.setHeader({ 'Content-Type': 'application/json' });
  11. app.get('/:table', function(req,res){
  12. connectionpool.getConnection(function(err, connection) {
  13. if (err) {
  14. console.error('CONNECTION error: ',err);
  15. res.statusCode = 503;
  16. res.send({
  17. result: 'error',
  18. err: err.code
  19. });
  20. } else {
  21. // query the database using connection
  22. }
  23. });
  24. });

When we encounter connection errors node.js will log them to the console and our app will respond with http status code 503 Service Unavailable with a mysql server error code.

Querying MySQL

Our routes will define a table name and if required an id, which we will use to build our query and return some json data.

Take a look at fetching the latest 20 rows;

  1. var express = require('express'),
  2. app = express(),
  3. mysql = require('mysql'),
  4. connectionpool = mysql.createPool({
  5. host : 'localhost',
  6. user : 'root',
  7. password : 'secret',
  8. database : 'rest_demo'
  9. });
  10. app.get('/:table', function(req,res){
  11. connectionpool.getConnection(function(err, connection) {
  12. if (err) {
  13. console.error('CONNECTION error: ',err);
  14. res.statusCode = 503;
  15. res.send({
  16. result: 'error',
  17. err: err.code
  18. });
  19. } else {
  20. connection.query('SELECT * FROM '+req.params.table+' ORDER BY id DESC LIMIT 20', req.params.id, function(err, rows, fields) {
  21. if (err) {
  22. console.error(err);
  23. res.statusCode = 500;
  24. res.send({
  25. result: 'error',
  26. err: err.code
  27. });
  28. }
  29. res.send({
  30. result: 'success',
  31. err: '',
  32. fields: fields,
  33. json: rows,
  34. length: rows.length
  35. });
  36. connection.release();
  37. });
  38. }
  39. });
  40. });
  41. app.get('/:table/:id', function(req,res){});
  42. app.post('/:table', function(req,res){});
  43. app.put('/:table/:id', function(req,res){});
  44. app.delete('/:table/:id', function(req,res){});
  45. app.listen(3000);
  46. console.log('Rest Demo Listening on port 3000');

Other than the error handling (which returns a http code 500) we have responded to the requester with up to 20 rows of data. 
They also get the field names and how many rows were returned.

Putting It All Together

Using the above technique we put together our server.js like so, which comes in at 175 lines in total.

Source GitHub

Note:

Do not use this in production, it is simply a demo.

The main issue is with the varible table name part in the routing, this is a BADidea.

The first thing I would change is encapsulion of each database table in its own js file under a routes directory, then require the needed js file for each request.

I hope you have enjoyed this demo - please leave your feedback below.

@NodeJS REST API with MySQL and Express http://t.co/NEvSjddwPz#nodewiz @codewiz_biz

— Codewiz.biz (@codewiz_biz) November 20, 2013

NodeJS REST API with MySQL and Express的更多相关文章

  1. Nodejs学习笔记(五)--- Express安装入门与模版引擎ejs

    目录 前言 Express简介和安装 运行第一个基于express框架的Web 模版引擎 ejs express项目结构 express项目分析 app.set(name,value) app.use ...

  2. Nodejs学习笔记(五)—Express安装入门与模版引擎ejs

    前言 前面也学习了一些Node.js的基本入门知道,现在开始进入Web开发的部分: Node.js提供了http模块,这个模块中提供了一些底层接口,可以直接使用,但是直接开发网站那还是太累了,所以ht ...

  3. 转 用C API 操作MySQL数据库

    用C API 操作MySQL数据库 参考MYSQL的帮助文档整理 这里归纳了C API可使用的函数,并在下一节详细介绍了它们.请参见25.2.3节,“C API函数描述”. 函数 描述 mysql_a ...

  4. .NET框架 - NETCORE + API + EF + MYSQL

    .NET框架 - NETCORE + API + EFCORE + MYSQL 1. 新建项目: 本文中使用 框架 .netcore2.2 . 2. 生成项目框架 3 安装MYSQL插件 点击“工具” ...

  5. nodejs cannot find module 'mysql' 问题分析

    在windows平台下,测试nodejs连接mysql数据库. 首先 在控制台中安装mysql依赖包 npm install mysql 安装成功后,mysql依赖包可以在User目录中的node_m ...

  6. C Mysql API连接Mysql

    最近都在查看MYsql C API文档,也遇到了很多问题,下面来简单的做一个总结. mysql多线程问题 mysql多线程处理不好,经常会发生coredump,见使用Mysql出core一文. 单线程 ...

  7. nodejs中如何使用mysql数据库[node-mysql翻译]

    nodejs中如何使用mysql数据库 db-mysql因为node-waf: not found已经不能使用,可以使用mysql代替. 本文主要是[node-mysql]: https://www. ...

  8. nodejs中如何连接mysql

    nodejs中如何连接mysql,下面给出一个小Demo. 第一步安装mysql模块npm install mysql 第二步导入mysql模块var mysql = require('mysql') ...

  9. nodejs使用sequelize操作mysql实例

    sequelize是node操作mysql的一款npm包,包含很多特性:数据库模型映射.事务处理.模型属性校验.关联映射等,花了两天时间学习了下基本的一些操作,特别是关联映射部分的操作,包含1:1.1 ...

随机推荐

  1. 在CentOS 7上构建RAID5、LVM和SAMBAserver(5)——架设SAMBAserver

    在CentOS 7上构建RAID5.LVM和SAMBAserver(5)--架设SAMBAserver 6. 架设SAMBAserver 6.1. 预备 本节的任务是配置SAMBA服务,共享/home ...

  2. vim调试

    首先,想调试一个程序的话,输入以下命令: guest-djjtew@ubuntu:~$ python3 -m pdb 1.py 这时候就停止了,等待着你的输入,然后输入"l"的话, ...

  3. iphone手机连接USB时出现须要Mobile device setup disk上的usbaapl.sys文件

    问题: iphone5 手机连接USB出现例如以下弹框 watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvYW5nZWwyMnh1/font/5a6L5L2T/ ...

  4. Linux的基本使用

    检测某个地址是否可以通信:ping xx.xx.xx.xx 检测某个端口是否开启:telnet xx.xx.xx.xx port 端口:用来区别不同服务 常用命令: 创建一个目录 /data mkdi ...

  5. Fakeapp2.2安装,使用简记

    1,硬件和操作系统,支持cuda的Nvidia显卡,8G及以上的内存,Windows10 x64(推荐,Windows7 x64亲测可行),可以使用gpu-z查看你的显卡详情 我的笔记本是双显卡(都是 ...

  6. Attempting to write a row[5] in the range [0,394] that is already written to disk.

    我用POI操作excel写数据,然后就报这个错了 XSSFWorkbook workbook = new XSSFWorkbook(); SXSSFWorkbook sxssfWorkbook = n ...

  7. Javascript MVC 学习笔记(二) 控制器和状态

    今天进入第二个部分:控制器. 控制器和状态 从以往的开发经验来看.我们都是将状态保存在server的session或者本地cookie中,但Javascript应用往往被限制在单页面,所以我们也能够将 ...

  8. RS485总线典型电路介绍

    一.RS485总线介绍: RS485总线是一种常见的串行总线标准,采用平衡发送与差分接收的方式,因此具有抑制共模干扰的能力.在一些要求通信距离为几十米到上千米的时候,RS485总线是一种应用最为广泛的 ...

  9. RNN 的入门程序DEMO

    1.视频介绍 https://www.youtube.com/watch?v=cdLUzrjnlr4 2. https://github.com/llSourcell/recurrent_neural ...

  10. linux 脚本统计代码行数

    由于实际需求,需要统计开源产品的代码行数,so,以下命令统计*.c的行数. .h,.java  .同理 find . -name *.c|xargs wc -l