Node.js+express的接口适配get和post并输出json

来源:互联网 发布:java编程工具 知乎 编辑:程序博客网 时间:2024/06/05 00:42

在上一篇Node.js.express的get和post输出json
例如post请求:

var dataSuccess = {    status: '100',     msg: '登录成功',    data: {        userId: '20170113',        userName: 'hgdqstudio',        blog: 'http://hgdqstudio.online'    }};var dataError = {    status: '99',     msg: '用户名或密码错误'};// 登录接口router.post('/login',function (req, res, next) {    // 打印post请求的数据内容    console.log(req.body);    console.log(req.body.username);    console.log(req.body.password);    if (req.body.username == "hgdqstudio" && req.body.password == "123456") {        res.end(JSON.stringify(dataSuccess));    } else {        res.end(JSON.stringify(dataError));    }});

但是这种接口,只能适应post这一种请求,如果我们希望后台给的接口支持postget
显然上一篇中提到了的router.getrouter.post都不能满足需求。
在express中支持的方式是很多的,具体可以看文档。
我们就需要改造了,用到app.all了。

// 登录接口router.all('/login',function (req, res, next) {    console.log(req.method);// 打印请求方式    if (req.method == "POST") {        var param = req.body;    } else{        var param = req.query || req.params;     }    console.log(param);    console.log(param.username);    console.log(param.password);    if (param.username == "hgdqstudio" && param.password == "123456") {        res.end(JSON.stringify(dataSuccess));    } else {        res.end(JSON.stringify(dataError));    }});

改造就很获取请求方式,饭后获取请求里面的参数:
post请求获取的参数是在body里面,
get请求获取的参数是在query里面,后面的params暂未发现有什么作用。
然后我们就可以在postman里面测试或是用Node.js.express的get和post输出json
提到的mui.ajax来测试【我使用的十MUI框架写的手机端界面】。

0 0