繁体   English   中英

使用 koa-router 获取请求参数

[英]GET request parameters with koa-router

http://localhost:3000/endpoint?id=83结果为 404(未找到)。 所有其他路线都按预期工作。 我在这里错过了什么吗?

router
  .get('/', function *(next) {
    yield this.render('index.ejs', {
      title: 'title set on the server'
    });
  })
  .get('/endpoint:id', function *(next) {
    console.log('/endpoint:id');
    console.log(this.params);
    this.body = 'Endpoint return';
  })

koa-router 参数文档

//Named route parameters are captured and added to ctx.params.

router.get('/:category/:title', function *(next) {
  console.log(this.params);
  // => { category: 'programming', title: 'how-to-node' }
});

角度控制器中的请求:

 $http.get('/endpoint', {params: { id: 223 }})
    .then(
      function(response){
        var respnse = response.data;
        console.log(response);
      }
  );

你的参数格式不对

用这个替换你的路线

.get('/endpoint/:id', function *(next) {
    console.log(this.params);
    this.body = 'Endpoint return';
  })

请求#query

.get('/endpoint/', function *(next) {
    console.log(this.query);
    this.body = 'Endpoint return';
  })

请求#param

.get('/endpoint/:id', function *(next) {
    console.log(this.params);
    this.body = 'Endpoint return';
  })

也许为时已晚,但对于那些还遇到这个问题的人来说,不是关键字this,而是ctx。 以下,当与url协商时

http://myweb.com/endpoint/45

 .get('/endpoint/:id', async (ctx, next) => {
     console.log(ctx.params);
     this.body = 'Endpoint return';   })

返回以下 json:

{ "id": "45"}

和这个:

 .get('/endpoint/:id', async (ctx, next) => {
     console.log(ctx.params.id);
     this.body = 'Endpoint return';   })

当使用相同的 url 进行咨询时返回

45

编辑:好消息是这两个端点确实不同。 您可以拥有两个端点,路由器可以根据您在浏览器中输入的 url 在两者之间做出决定。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM