Node - Egg.js 框架从入门到放弃系列(3)- 主要的几种传参方式

本文为我的学习整理所得,但愿对读者有所帮助。javascript

GET

传递参数

在通常状况下,项目中会有两种get传参方式:1 是以?&分割的、2 是以/分割;html

例如客户端向传递约定的idname这两个参数:java

  1. localhost:7001/goods/detail?id=2333&name=hefennode

  2. localhost:7001/goods/detail/2333/hefengit

接收参数

对应的,在服务器接收这两个参数的方式:1 query方式、2 params,如下是代码示例:github

  1. app/controllergoods.js中,新建一个函数detail
// GET
  async detail() {
    const { ctx } = this;
    console.log(ctx.query);
    ctx.body = `hello, my id is ${ctx.query.id} and my name is ${ctx.query.name}`;
  }
复制代码

浏览器中输入连接1 -- localhost:7001/goods/detail?id=2333&name=hefen,能够看到界面已经把数据读取出来了:json

这时候咱们再看控制台的打印结果:浏览器

  1. app/controllergoods.js中,再新建一个函数detailTwo
// GET
  async detailTwo() {
    const { ctx } = this;
    console.log(ctx.params);
    ctx.body = `hello, detailTwo, my id is ${ctx.params.id} and my name is ${ctx.params.name}`;
  }
复制代码

而后在app/router.js中加入新的路由:服务器

router.get('/goods/detailTwo/:id/:name', controller.goods.detailTwo);
复制代码

浏览器中输入连接2 -- localhost:7001/goods/detailTwo/2333/hefen,能够看到界面已经把数据读取出来了:
这时候咱们再看控制台的打印结果:

POST

由于POST请求不能直接在浏览器模拟,因此接下来咱们会借助了接口神器 postman 来测试接口。 固然直接发送请求的话会触发egg.js内置的csrf防护机制,控制台报错以下图:(PS:更多防护机制请看官方文档点击此处)app

这个时候咱们须要在config/config.default.js中配置一下,就能够正常使用了

config.security = {
    csrf: {
      enable: false, //此处关闭csrf防护
    }
}
复制代码

传递参数

用postman选择POST方式,输入接口localhost:7001/goods/detail/createGood,勾选body,raw,JSON格式,填入json对象后,点击发送,以下图:

接收参数

app/controllergoods.js中,新建一个函数createGood

// POST
  async createGood() {
    const { ctx } = this;
    const { name, id } = ctx.request.body;
    console.log(ctx.request.body);
    ctx.body = {
      id:`back ${id}`,
      name:`back ${name}`,
    }
  }
复制代码

而后在app/router.js中加入新的路由:

router.post('/goods/createGood', controller.goods.createGood);
复制代码

在postman中点击发送后,咱们就能够看到返回了postman获得了返回参数

这时候咱们再看控制台的打印结果:

PUT、DELETE

这两种的调用方式与上面的请求大同小异,须要的童鞋能够看我在github放出的源码。

一块儿作项目

这节如要熟悉请求方式,因此。。

PS:所有的代码仓库:github.com/hejian1993/…,暂时没有分章节,仅供参考。

我是河粉,咱们下一节见

三个月前,一我的关注了我,他娶了一个如花似玉的老婆。 一周前,一我的关注了我,他中了888亿。 今年,关注了个人人都娶了如花似玉的老婆结婚那天还中888亿。 我已开过光,话已经放到这了。

相关文章
相关标签/搜索