首页 > 技术文章 > 接口api文档生成

lhongsen 2021-05-10 23:34 原文

  1. 全局安装apidoc
npm install apidoc -g
  1. 配置apidoc.json
{
  "name": "test",
  "version": "0.1.0",
  "description": "练习写接口文档",
  "title": "学习编写api文档",
  "url" : "http://127.0.0.1:3001"
}
  1. 使用
    把该注释写在接口的前面
/**
 * @api {get} /user/:id Request User information
 * @apiName GetUser
 * @apiGroup User
 *
 * @apiParam {Number} id Users unique ID.
 *
 * @apiSuccess {String} firstname Firstname of the User.
 * @apiSuccess {String} lastname  Lastname of the User.
 */

例子:

/**
 * @api {post} /user/reg  用户注册 
 * @apiName  用户注册
 * @apiGroup User
 *
 * @apiParam {String} us 用户名
 * @apiParam {String} ps 用户密码
 * @apiParam {String} code 验证码 
 *
 * @apiSuccess {String} firstname Firstname of the User.
 * @apiSuccess {String} lastname  Lastname of the User.
 */
router.post('/reg', (req, res) => {
    // 获取数据
    let { us, ps, code } = req.body;
    console.log(us, ps, code);
    if (!us || !ps || !code) {
        return res.send({
            err: -1,
            msg: '参数错误'
        })
    }
    // if (!us || ps) { return res.send({ err: -1, msg: '参数错误' }) };
    if (us && ps && code) {
        // 判断验证码是否ok
        console.log(codes[us], code, codes);
        if (codes[us] != code) {
            return res.send({ err: -4, msg: '验证码错误' });
        }
        User.find({ us })
            .then((data) => {
                if (data.length === 0) {
                    // 用户名不存在,可以注册
                    return User.insertMany({ us: us, ps: ps });
                } else {
                    res.send({
                        err: -3,
                        msg: '用户名已存在 '
                    })
                }
            })
    } else {
        return res.send({ err: -2, msg: '参数错误' });
    }
});

生成api稳定执行命令:
-i: 是指生成api文档
./: 是指生成api文档的当前目录
-o: 是指api文档输出
./apidoc: 是指生成的api文档放在当前的apidoc文件夹下

apidoc -i ./ -o ./apidoc

官网地址:https://apidocjs.com/#configuration
中文:https://blog.csdn.net/whatday/article/details/84590795

推荐阅读