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

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

3、源码

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

/*
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端口。提示:

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

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

$ curl http://127.0.0.1:4000/

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

  % 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请求:

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

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

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

返回信息为:

  % 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 周六 凌晨

发布了481 篇原创文章 · 获赞 244 · 访问量 110万+

猜你喜欢

转载自blog.csdn.net/subfate/article/details/102617463
今日推荐