0
点赞
收藏
分享

微信扫一扫

egg 项目里编写基础的 GET 接口:使用 GET 请求参数获取


需求

比如我们想要实现:​​http://127.0.0.1:7001/user/kaimo​​​,想获取到用户信息的id:​​kaimo​​ 到页面

egg 项目里编写基础的 GET 接口:使用 GET 请求参数获取_前端

实现

1、配置路由

'use strict';

/**
* @param {Egg.Application} app - egg application
*/
module.exports = app => {
const { router, controller } = app;
router.get('/', controller.home.index);
router.get('/user/:id', controller.home.user);
};

egg 项目里编写基础的 GET 接口:使用 GET 请求参数获取_用户信息_02

2、编写控制层

'use strict';

const Controller = require('egg').Controller;

class HomeController extends Controller {
async index() {
const { ctx } = this;
ctx.body = 'hi, egg';
}
async user() {
const { ctx } = this;
ctx.body = 'user 页面';
}
}

module.exports = HomeController;

egg 项目里编写基础的 GET 接口:使用 GET 请求参数获取_node.js_03

3、刷新页面

egg 项目里编写基础的 GET 接口:使用 GET 请求参数获取_javascript_04

4、获取 user 后面的参数

我们可以通过 ​​ctx.params​​ 的方式拿到

egg 项目里编写基础的 GET 接口:使用 GET 请求参数获取_刷新页面_05

然后修改一下代码就可以获得

'use strict';

const Controller = require('egg').Controller;

class HomeController extends Controller {
async index() {
const { ctx } = this;
ctx.body = 'hi, egg';
}
async user() {
const { ctx } = this;
const { id } = ctx.params;
ctx.body = id;
}
}

module.exports = HomeController;

egg 项目里编写基础的 GET 接口:使用 GET 请求参数获取_javascript_06


举报

相关推荐

0 条评论