用 Node.js 快速开发 RESTful API

前面讲了用 Node.js 开发静态网页服务,这一篇讲用 Node.js 开发 RESTful API 服务,同样是基于 express 框架。

Node 返回 json

比如开发一个用户信息接口,通过 get 方法返回用户信息:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
var express = require('express')
var app = express()

var json = {
code: 200,
msg: '请求成功',
data: {
userId: '123456',
name: 'Terry',
blog: 'https://yunm.coding.me'
}
}

app.get("/", function (req, res) {
res.send(json)
})

app.listen(5438, function () {
console.log("启动服务 http://localhost:5438 ")
})

运行代码,打开 http://localhost:5438 ,就可以看到返回的 json:

Node 连接 MySQL 数据库

Node 可以很方便地从 MySQL 数据库查询数据并返回,例如查询年龄为 20 的用户信息,封装成 RESTful 接口:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
var express = require('express');
var app = express();
var mysql = require('mysql');

var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : 'xxxx',
database : 'userdb'
});

connection.connect();
connection.query('select * from user where age=20', function (error, results) {
if (error) throw error;
app.get('/',function (req, res) {
res.send(results);
})
});

app.listen(5000, function () {
console.log('启动服务 http://localhost:5000');
});

运行代码,打开 http://localhost:5000 ,就可以看到返回的 json:

当然了,Node.js 在分布式系统开发方面并不成熟,现阶段 node 貌似更适合快速开发小型服务,大型系统还是要用 Spring Cloud 等做服务注册发现,做高可用。