nodejs实践录:使用curl测试post请求

以前与后台交互的json接口,都是用postman工具来测试的,后来发现curl命令也可以发post或get请求。本文利用koa创建web服务器,对外提供了几个URL,然后用curl进行测试。

3、源码

完整源码如下,假设源码文件名称为koa_test.js

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
/*
koa简单示例,主要是post、get请求
使用postman可以发送,
也可以使用curl命令,但需要组装多一点内容。并且json的字段全部要用括号。

*/

const koa_router = require("koa-router");
const Koa = require("koa");
const koa_bodyparser = require("koa-bodyparser");

const log = require('../lib/log.js')

const router = koa_router();

const g_port = 4000;

/*
curl http://127.0.0.1:4000/
*/
router.get('/', async (ctx) =>
{
ctx.type = 'html';
ctx.body = '\r\nwelcome to koa';
});

router.get("/status",async (ctx) => {
const now = new Date();
ctx.body = `api-service lives! (${now})`;
});

router.get('/about', async (ctx) =>
{
ctx.type = 'html';
ctx.body = '<a href="/">About Page</a>';
});

router.get('/about/foobar', async (ctx) =>
{
ctx.type = 'html';
ctx.body = 'here is /about/foobar';
});

router.post("/set", async (ctx) => {
log.print('got: ', ctx.request.body); // 此处解析到传递的json
var res = new Object();
res['ret'] = 0;
ctx.body = res; // 返回的是json,正常
});

function main()
{
var app = new Koa();
app.use(koa_bodyparser({
enableTypes:["json","test","form"],
onerror:function (err,ctx){
log.print("api service body parse error",err);
ctx.throw(400,"body parse error");
},
}));

app.use(router.routes());
app.listen(g_port);
console.log('Running a koa server at localhost: ', g_port)

}

main();

4、测试

首先执行node koa_test.js.js运行服务器,成功后,监听4000端口。提示:

1
2
$ node koa_test.js
Running a koa server at localhost: 4000

接着另起一个终端执行curl命令。由于本文在windows下测试,所以一共打开2个git bash。
使用curl发送get命令:

1
$ curl http://127.0.0.1:4000/

服务器处理响应后返回信息,如下:

1
2
3
4
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
Dload Upload Total Spent Left Speed
100 16 100 16 0 0 16000 0 --:--:-- --:--:-- --:--:-- 16000
welcome to koa

使用curl发送post请求:

1
curl http://127.0.0.1:4000/set -X POST -H "Content-Type:application/json" -d  '{"cmd":"set","content":"foobar"}'

服务器处理响应,此处简单打印curl传递的json数据:

1
[2019-10-17 16:25:48.337]  got:  { cmd: 'set', content: 'foobar' }

返回信息为:

1
2
3
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
Dload Upload Total Spent Left Speed
100 41 100 9 100 32 145 516 --:--:-- --:--:-- --:--:-- 661{"ret":0}

5、小结

curl使用轻便,可应付简单的测试场合。如果是get请求,只传递URL(加端口)和URL地址即可。如果是post请求,除了URL外,需用-X POST指定为post请求,并用-H "Content-Type:application/json"指定为json格式。最后,使用-d指定json数据,注意,json数据的每个字段均需要括号,并且最外层需要大括号{}。否则,无法正常解析。

李迟 2019.10.17 周六 凌晨