介紹兩種方式做mock的server: – Express for mock – json-server

express for mock

因為我們要實現restful風格的api, 所以我們需要構建服務器。這里我們用到了express。

express

高度包容,快速而極簡的 Node.js Web框架

express 一種保持最低程度規模的靈活 Node.js Web應用框架,它提供精簡基本Web應用程序功能,而不會隱藏你了解Node.js功能。

1. 安裝

 npm init //創建一個package.json
npm install express --save

2. 原理

2.1 http模塊

Express建立在 Node.js 內置的http模塊上。

如果用http模塊生成服務器如下:

var http = require('http');
var app = http.createServer(function(request, response) {
response.writeHead(200, {"Content-Type": "text/plain"});
response.end("Hello world");
});
app.listen(3000, "localhost");

express封裝(核心是對http模塊的再包裝)

var express = require('express');
var app = express();
app.get('/', function(req, res) {
res.send("Hello world");
});
app.listen(3000):

Express 框架等價于在http模塊之上,加了一個中間層.

2.2 中間件

middleware 就是處理HTTP請求的函數。其特點就是,一個中間件處理完,再傳遞給下一個中間件。

從本質上講,一個express就是在調用各種中間件。 中間件的種類:

var router = express.Router();
app.use(function(err, req, res, next) {
console.log(err.stack);
res.status(500).send('Something broke!');
})
var options = {
dotfiles: 'ignore',
etag: false,
extensions: ['htm', 'html'],
index: false,
maxAge: '1d',
redirect: false,
setHeaders: function (res, path, stat) {
res.set('x-timestamp', Date.now());
}
};

app.use(express.static('public', options));

每個目錄可有多個靜態目錄:

 app.use(express.static('public'));
app.use(express.static('uploads'));
app.use(express.static('files'));

npm install cookie-parser //先安裝所需node模塊

var cookieParser = require('cookie-parser');
app.user(cookieParser());

Router

路由是由一個 URI、HTTP 請求(GET、POST等)和若干個句柄組成,它的結構如下: app.METHOD(path, [

基本路由

 var express = require('express');
var app = express();

// respond with "hello world" when a GET request is made to the homepage

app.get('/', function(req, res) {
res.send('hello world');
});

路由方法

// GET method route
app.get('/', function (req, res) {
res.send('GET request to the homepage');
});

// POST method route
app.post('/', function (req, res) {
res.send('POST request to the homepage');
});

//....get, post, put, head, delete, options, trace, copy....

app.all('/secret', function (req, res, next) {
console.log('Accessing the secret section ...');
next(); // pass control to the next handler
});

他可以是字符串,字符串模式,正則表達式。

 app.get('/', function(req, res) {...}); // 匹配根路徑的請求
app.get('/about', function(req, res) {...});// 匹配 /about 路徑的請求
app.get('/help.json', function(req, res) {...});// 匹配 /random.text 路徑的請求

app.get('/ab?cd', function(req, res) {...});// 匹配 acd 和 abcd
app.get('/ab+cd', function(req, res) {...});// 匹配 abcd、abbcd、abbbcd等
app.get('/ab * cd', function(req, res) {...});// 匹配 abcd、abxcd、abRABDOMcd、ab123cd等
app.get('/ab(cd)?e', function(req, res) {...});// 匹配 /abe 和 /abcde

app.get('/a/', function(req, res) {...});// 匹配任何路徑中含有 a 的路徑:
app.get('/.*fly$', function(req, res) {...});// 匹配 butterfly、dragonfly,不匹配 butterflyman、dragonfly man等

Express路由路徑用的是path-to-regexp

 var cb0 = function (req, res, next) {
console.log('CB0');
next();
}

var cb1 = function (req, res, next) {
console.log('CB1');
next();
}

var cb2 = function (req, res) {
res.send('Hello from C!');
}

app.get('/example/c', [cb0, cb1, cb2]);
app.get('/example/c', [cb0, cb1], function(req, res) {

});

創建路由路徑的鏈式句柄

 app.route('/book')
.get(function(req, res) {
res.send('Get a random book');
})
.post(function(req, res) {
res.send('Add a book');
})
.put(function(req, res) {
res.send('Update the book');
});

中間件

//birds.js

var express = require('express');
var router = express.Router();

// 該路由使用的中間件
router.use(function timeLog(req, res, next) {
console.log('Time: ', Date.now());
next();
});
// 定義網站主頁的路由
router.get('/', function(req, res) {
res.send('Birds home page');
});
// 定義 about 頁面的路由
router.get('/about', function(req, res) {
res.send('About birds');
});

module.exports = router;
var birds = require('./birds');
...
app.use('/birds', birds);

應用即可處理發自 /birds 和 /birds/about 的請求

faker.js

用來mock數據,有自己的API,而且非常豐富

install

npm i faker --save

var faker = require('faker');

var randomName = faker.name.findName();
var randomEmail = faker.internet.email();
var randomCard = faker.helpers.createCard();

API

Faker.fake()

var json = faker.fake("{{name.lastName}}, {{name.firstName}}, {{name.suffix}}");
console.log(json) //"Marks, Dean Sr."

Localization

default value is set to English

faker.locale = "zh_CN";

demo

var Faker  = require('faker');
var _ = require('lodash');
Faker.locale="zh_CN";
console.log(Faker, 'faker');

var data = [];
_.times(10, function() {
var temp = {
name: Faker.name.findName(),
emial: Faker.internet.email(),
website: Faker.internet.url(),
image: Faker.image.avatar()
};
data.push(temp);
})

module.exports = {
errcode: 0,
errmsg: 'success',
data: {
list: data
}
}

json-server for mock

install

npm install json-server --save

創建數據文件

//db.json
{
"posts": [
{
id: 1,
title: 'json-server'
},
{
id: 2,
title: "mock"
}
],
"comments": [
{
id: 1,
content: "very good !",
postId: 1
}
],
"profile": {
"name": "yulong"
}
}

運行

安裝完后,在本目錄下創建一個xx.json,然后執行

json-server db.json -p 3003

默認端口是3000

json-server [options] <source>
Options:
--config, -c 指定 config 文件 [默認: "json-server.json"]
--port, -p 設置端口號 [default: 3000]
--host, -H 設置主機 [默認: "0.0.0.0"]
--watch, -w 監控文件 [boolean]
--routes, -r 指定路由文件
--static, -s 設置靜態文件
--read-only, --ro 只允許 GET 請求 [boolean]
--no-cors, --nc 禁止跨域資源共享 [boolean]
--no-gzip, --ng 禁止GZIP [boolean]
--snapshots, -S 設置快照目錄 [默認: "."]
--delay, -d 設置反饋延時 (ms)
--id, -i 設置數據的id屬性 (e.g. _id) [默認: "id"]
--quiet, -q 不輸出日志信息 [boolean]
--help, -h 顯示幫助信息 [boolean]
--version, -v 顯示版本號 [boolean]

然后訪問: http://locahost:3000/posts

[
{
id: 1,
title: 'json-server'
},
{
id: 2,
title: "mock"
}
]

本文章轉載微信公眾號@云前端

上一篇:

使用Express.js構建一個簡單的RESTful API,處理CRUD操作

下一篇:

使用 ChatGPT 和 json-server 快速實現 mock API
#你可能也喜歡這些API文章!

我們有何不同?

API服務商零注冊

多API并行試用

數據驅動選型,提升決策效率

查看全部API→
??

熱門場景實測,選對API

#AI文本生成大模型API

對比大模型API的內容創意新穎性、情感共鳴力、商業轉化潛力

25個渠道
一鍵對比試用API 限時免費

#AI深度推理大模型API

對比大模型API的邏輯推理準確性、分析深度、可視化建議合理性

10個渠道
一鍵對比試用API 限時免費