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.
- var express = require('express'),
- app = express(),
- mysql = require('mysql');
- app.listen(3000);
- console.log('Rest Demo Listening on port 3000');
DB Connection
Setup your database and create a pool of connections to MySQL server;
- var express = require('express'),
- app = express(),
- mysql = require('mysql'),
- connectionpool = mysql.createPool({
- host : 'localhost',
- user : 'root',
- password : 'secret',
- database : 'rest_demo'
- });
- app.listen(3000);
- 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.
- var express = require('express'),
- app = express(),
- mysql = require('mysql'),
- connectionpool = mysql.createPool({
- host : 'localhost',
- user : 'root',
- password : 'secret',
- database : 'rest_demo'
- }),
- res.setHeader({ 'Content-Type': 'application/json' });
- app.get('/:table', function(req,res){});
- app.get('/:table/:id', function(req,res){});
- app.post('/:table', function(req,res){});
- app.put('/:table/:id', function(req,res){});
- app.delete('/:table/:id', function(req,res){});
- app.listen(3000);
- 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.
- var express = require('express'),
- app = express(),
- mysql = require('mysql'),
- connectionpool = mysql.createPool({
- host : 'localhost',
- user : 'root',
- password : 'secret',
- database : 'rest_demo'
- });
- res.setHeader({ 'Content-Type': 'application/json' });
- app.get('/:table', function(req,res){
- connectionpool.getConnection(function(err, connection) {
- if (err) {
- console.error('CONNECTION error: ',err);
- res.statusCode = 503;
- res.send({
- result: 'error',
- err: err.code
- });
- } else {
- // query the database using connection
- }
- });
- });
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;
- var express = require('express'),
- app = express(),
- mysql = require('mysql'),
- connectionpool = mysql.createPool({
- host : 'localhost',
- user : 'root',
- password : 'secret',
- database : 'rest_demo'
- });
- app.get('/:table', function(req,res){
- connectionpool.getConnection(function(err, connection) {
- if (err) {
- console.error('CONNECTION error: ',err);
- res.statusCode = 503;
- res.send({
- result: 'error',
- err: err.code
- });
- } else {
- connection.query('SELECT * FROM '+req.params.table+' ORDER BY id DESC LIMIT 20', req.params.id, function(err, rows, fields) {
- if (err) {
- console.error(err);
- res.statusCode = 500;
- res.send({
- result: 'error',
- err: err.code
- });
- }
- res.send({
- result: 'success',
- err: '',
- fields: fields,
- json: rows,
- length: rows.length
- });
- connection.release();
- });
- }
- });
- });
- app.get('/:table/:id', function(req,res){});
- app.post('/:table', function(req,res){});
- app.put('/:table/:id', function(req,res){});
- app.delete('/:table/:id', function(req,res){});
- app.listen(3000);
- 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的更多相关文章
- Nodejs学习笔记(五)--- Express安装入门与模版引擎ejs
目录 前言 Express简介和安装 运行第一个基于express框架的Web 模版引擎 ejs express项目结构 express项目分析 app.set(name,value) app.use ...
- Nodejs学习笔记(五)—Express安装入门与模版引擎ejs
前言 前面也学习了一些Node.js的基本入门知道,现在开始进入Web开发的部分: Node.js提供了http模块,这个模块中提供了一些底层接口,可以直接使用,但是直接开发网站那还是太累了,所以ht ...
- 转 用C API 操作MySQL数据库
用C API 操作MySQL数据库 参考MYSQL的帮助文档整理 这里归纳了C API可使用的函数,并在下一节详细介绍了它们.请参见25.2.3节,“C API函数描述”. 函数 描述 mysql_a ...
- .NET框架 - NETCORE + API + EF + MYSQL
.NET框架 - NETCORE + API + EFCORE + MYSQL 1. 新建项目: 本文中使用 框架 .netcore2.2 . 2. 生成项目框架 3 安装MYSQL插件 点击“工具” ...
- nodejs cannot find module 'mysql' 问题分析
在windows平台下,测试nodejs连接mysql数据库. 首先 在控制台中安装mysql依赖包 npm install mysql 安装成功后,mysql依赖包可以在User目录中的node_m ...
- C Mysql API连接Mysql
最近都在查看MYsql C API文档,也遇到了很多问题,下面来简单的做一个总结. mysql多线程问题 mysql多线程处理不好,经常会发生coredump,见使用Mysql出core一文. 单线程 ...
- nodejs中如何使用mysql数据库[node-mysql翻译]
nodejs中如何使用mysql数据库 db-mysql因为node-waf: not found已经不能使用,可以使用mysql代替. 本文主要是[node-mysql]: https://www. ...
- nodejs中如何连接mysql
nodejs中如何连接mysql,下面给出一个小Demo. 第一步安装mysql模块npm install mysql 第二步导入mysql模块var mysql = require('mysql') ...
- nodejs使用sequelize操作mysql实例
sequelize是node操作mysql的一款npm包,包含很多特性:数据库模型映射.事务处理.模型属性校验.关联映射等,花了两天时间学习了下基本的一些操作,特别是关联映射部分的操作,包含1:1.1 ...
随机推荐
- CSDN - 进程结束后new出的内存会回收吗?
http://blog.csdn.net/stanjiang2010/article/details/5386647 关键词:内存回收
- iOS移动开发周报-第19期
iOS移动开发周报-第19期 前言 欢迎国内的iOS同行或技术作者向我提交周报线索,线索可以是新闻.教程.开发工具或开源项目,将相关文章的简介和链接在微博上发布并 @唐巧_boy 即可. [摘要]:本 ...
- iperf3 测试路由器吞吐率
mini newifi 电脑端: iperf3 -s 路由器: root@OpenWrt:/# iperf3 -c 10.10.10.3 -t 20 Connecting to host 10.10. ...
- C#注冊表操作汇总
一.注冊表基本知识 1) 结构 键->项->子项->值项(名称.类型.数据) REG_SZ 字符串 REG_BINARY 二进制 REG_DWORD ...
- Android版App的控件元素定位
前言 如何获取页面上各控件元素,无论是Web自动化还是App自动化,此步骤都是非常关键的! Web页面的控件元素可通过开发者选项(Chrome浏览器的F12)来协助定位,App端也是有相应的工具来协助 ...
- Struts2 原理(转载)
图来源于Struts2官方站点,是Struts 2 的整体结构. Struts2框架由3个部分组成:核心控制器FilterDispatcher.业务控制器和用户实现的业务逻辑组件.在这3个部分里,St ...
- 第 2 章 第 9 题 顺序 & 二分搜索效率分析问题
问题分析 顺序搜索的时间复杂度是O( n ),二分搜索的时间复杂度级别是O( lgn ).但这并不代表二分的时间开销就一定比顺序的小,因为二分搜索有个前提:元素必须要是有序的.如果仅仅为了二分搜索几个 ...
- Oracle学习(十三):闪回
1.知识点:能够对比以下的录屏进行阅读 SQL> --1. 错误地删除了记录 SQL> --2. 错误地删除了表 SQL> --3. 查询历史记录 SQL> --4. 怎样撤销 ...
- Android Material Design 中文版
http://www.google.com/design/spec/animation/authentic-motion.html http://www.oschina.net/question/14 ...
- EasyPusher安卓Android手机直播推送之RTSP流媒体协议流程
EasyPusher移动端推送同我们平时用的RTSP直播推送流程一样,都是采用标准RTSP/RTP推送流程:ANNOUNCE->SETUP->PLAY->RTP/RTCP->T ...