NodeJS REST API with MySQL and Express

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

时间: 2024-11-05 16:32:46

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

使用nodeJS创建API接口,连接mysql数据库(新手向简易版)

博主在学习安卓课程做期末程序的时候就一直想自己做API了,结果网上的教程感觉都太杂,很多都文不对题,找不到一个明确的思路,结果就只能放弃改用jdbc实现数据库交互,现在学了前端,又接触了一点nodeJS之后,才终于有了思路,最近也成功给自己放在服务器上的网站部署了API.现在就来分享一下,也顺便给自己留个备份. ps:只是自己突然想到的做法,而且个人觉得真的是简易版,可能不标准,但亲测能用. 一.前期准备 首先声明:不懂也没关系,直接仿照代码,需要修改的地方我会用红色标注出来,不过mysql一定

nodejs cannot find module 'mysql' 问题分析

在windows平台下,测试nodejs连接mysql数据库. 首先 在控制台中安装mysql依赖包 npm install mysql 安装成功后,mysql依赖包可以在User目录中的node_modules文件夹中找到 然后新建一个测试mysql连接的js文件mysqltest.js var mysql = require('mysql'); var connect = mysql.createConnection({ host:'localhost', user:'root', pass

nodejs中如何连接mysql

nodejs中如何连接mysql,下面给出一个小Demo. 第一步安装mysql模块npm install mysql 第二步导入mysql模块var mysql = require('mysql'); 第三步连接mysql数据库var connection = mysql.createConnection({    host:'localhost',    user:'root',    password:'',    database:'yudi'}); connection.connect

nodejs使用sequelize操作mysql实例

sequelize是node操作mysql的一款npm包,包含很多特性:数据库模型映射.事务处理.模型属性校验.关联映射等,花了两天时间学习了下基本的一些操作,特别是关联映射部分的操作,包含1:1.1:N.N:N部分,利用express框架实现简单的rest服务. 关于项目结构: 其中,routes存放各种路由,models配置各种数据库模型类,ref.js用来配置相关的数据模型关联关系,主要关系为:user和loginInfo是1:1.user和address是1:N.user和role是N:

VC++通过API连接MySQL

1.  首先安装MySQL数据库服务器,本文安装的是mysql-installer-community-5.6.10.1.msi这个版本,至于各个版本有什么不同,不在这里说明. 如下的默认安装的安装目录结构截图: 2. 接着配置环境变量,这个纯粹是要为了在命令行下使用mysql的相关命令更加方便.如 如下设置即可,有些安装包已经自动给添加上了这个路径,只需要检查一下即可. 3. 先在命令行下创建一个数据samp_db,并在创建表students.建库和建表都相对简单,如下截图是已经建好的. 创建

[MEAN Stack] First API with Node.js, Express and MongoDB

Learn how to import data into your MongoDB and then use Express to serve a simple Node.js API. Import data into MongoDB: For exmaple, you have an data.json file and contains some data. 1. Start Mongod service: //in the cmd $ mongod 2. Open a new Tab,

使用nodejs搭建api的mock服务

1. 介绍 公司的业务开发都是静态页面,开发前期总是避免不了获取api的问题.在vue中有一些mockjs的方案,方案都是注入性质的,和最终部署总是有差别,而且业务大部分还在zepto下,很难找到合适的方案.而开发前期调整css样式需要真实的dom,不能总是写个静态页面来调试.正好利用koa2的便利性,搭建一个mock服务. 在线的mock服务其实还是不少的,大部分都是以 url路径作区分API的名字,对于普通的API是够用了,但对于根据输入参数作为API名称的情况,就没有办法了.比如我们公司的

C API向MySQL插入批量数据的快速方法——关于mysql_autocommit

MySQL默认的数据提交操作模式是自动提交模式(autocommit).这就表示除非显式地开始一个事务,否则每个查询都被当做一个单独的事务自动执行.我们可以通过设置autocommit的值改变是否是自动提交autocommit模式.查询当前数据库事务提交方式的命令为: mysql> show variables like 'autocommit'; +---------------+-------+ | Variable_name | Value | +---------------+-----

nodejs学习笔记一:安装express框架并构建工程目录

偶遇node是在一个阳光明媚的上午,无意间打开博客看到一片关于nodejs的介绍,通读全篇后,心情跌宕起伏,哎呀,这么好的东西我竟然现在才知道,这是最气的,于是马上开始制定学习nodejs计划,好了,话不多说,开始我的学习记录. 想要学习node首先开发环境不可少,下面就记录一下安装express框架和构建第一个node工程项目(跳过安装nodejs环境,因为已经装过,nodejs.org下载对应的安装包下一步傻瓜化安装): 1.安装express express是nodejs上最流行的web开