0%

Node.js 模拟本地接口测试环境以及简单的代理转发服务

为方便测试小哥调试,用 Node.js 模拟了一些简单的接口测试业务场景。

Koa 简单模拟服务器

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
const Koa = require('koa');
const KoaBodyParser = require('koa-bodyparser');
const KoaRouter = require('koa-router');

const app = new Koa();
const router = new KoaRouter();

app.use(KoaBodyParser());

app.use(async (ctx, next) => {
const { path, method } = ctx;
console.log({ ctx });
// ctx.set('Access-Control-Allow-Origin', '*');
// ctx.set('Content-Type', 'application/json');
let status = Number(path?.split('/')[1] ?? 200) || 400;
ctx.status = status;
ctx.body = {
path,
url: ctx.request.url,
status,
method,
data: {
body: ctx.request.body,
query: ctx.request.query,
querystring: ctx.request.querystring
},
msg: `${method}[${path}](请求完成-${status})`
};
await new Promise((resolve) => {
setTimeout(() => {
resolve();
}, 2000);
});
await next();
});

// const cors = require('koa-cors');
// app.use(cors());

// router.post('/post', async (ctx, next) => {
// const { path, method } = ctx;
// let data = {
// body: ctx.request.body,
// query: ctx.request.query,
// querystring: ctx.request.querystring
// };
// ctx.body = {
// status: 200,
// path,
// method,
// data,
// msg: 'POST test'
// };
// await next();
// });
// router.get('/hello/:name', async (ctx, next) => {
// let name = ctx.params.name;
// const { path, method } = ctx;
// let data = {
// body: ctx.request.body,
// query: ctx.request.query,
// querystring: ctx.request.querystring
// };
// ctx.body = {
// status: 200,
// path,
// method,
// data,
// msg: `get ${name}`
// };
// await next();
// });
// app.use(router.routes());

app.on('error', (err) => {
console.log('server error', err);
});

app.listen(666);

console.log('app started at port 666...');

Express 简单模拟服务器

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
const express = require('express');
const bodyParser = require('body-parser');

const app = express();

app.all('*', function (req, res, next) {
res.header('Access-Control-Allow-Origin', req.headers.origin || '*');
res.header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
res.header('Access-Control-Allow-Credentials', true);
res.header('Content-Type', 'application/json;charset=utf-8');
next();
});

// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }));
// parse application/json
app.use(bodyParser.json());

app.post('/post/:name', function (req, res) {
res.status(200).send({
status: 200,
path: req.path,
url: req.url,
method: req.method,
data: {
body: req.body,
query: req.query,
querystring: req.originalUrl.split('?')[1],
params: req.params
},
msg: 'POST test'
});
});

const server = app.listen(888, function () {
let host = server.address().address;
let port = server.address().port;

console.log('server:http://localhost:%s', port);
});

Koa+Request 代理转发请求

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
const request = require('request');
const Koa = require('koa');
const KoaRouter = require('koa-router');
const cors = require('koa-cors');

const app = new Koa();
const router = new KoaRouter();
app.use(cors());

router.get('/get', async (ctx, next) => {
return new Promise((resolve) =>
request(
{
url: 'http://localhost:666/hello/world?q=123',
method: 'GET',
json: true,
headers: {
'Content-Type': 'application/json'
},
body: ctx.request.body
},
function (error, response, body) {
ctx.status = response.statusCode;
if (error) {
console.log('---------------ERROR----------------');
console.log(error);
ctx.body = error;
resolve(next());
console.log('---------------ERROR----------------');
} else {
console.log('---------------SUCCESS----------------');
console.log(body);
ctx.body = body;
resolve(next());
console.log('---------------SUCCESS----------------');
}
}
)
);
});

app.use(router.routes());

app.on('error', (err) => {
console.log('server error', err);
});

app.listen(10010);
console.log('proxy started at port 10010...');

Express+Request 代理转发请求

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
const request = require('request');
const express = require('express');

const app = express();

app.all('*', function (req, res, next) {
res.header('Access-Control-Allow-Origin', req.headers.origin || '*');
res.header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
res.header('Access-Control-Allow-Credentials', true);
res.header('Content-Type', 'application/json;charset=utf-8');
next();
});

app.get('/get', (req, res) => {
request(
{
url: 'http://localhost:666/hello/world?q=123',
method: 'GET',
json: true,
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(req.body)
},
function (error, response, body) {
if (error) {
console.log('---------------ERROR----------------');
console.log(error);
res.status(response.statusCode).send(error);
res.end();
console.log('---------------ERROR----------------');
} else {
console.log('---------------SUCCESS----------------');
console.log(body);
res.status(response.statusCode).send(body);
res.end();
console.log('---------------SUCCESS----------------');
}
}
);
});

app.listen(10086);
console.log('proxy started at port 10086...');
bulb