简体   繁体   English

使用 koa-router 获取请求参数

[英]GET request parameters with koa-router

http://localhost:3000/endpoint?id=83 results in 404 (Not Found). http://localhost:3000/endpoint?id=83结果为 404(未找到)。 All other routes work as expected.所有其他路线都按预期工作。 Am I missing something here?我在这里错过了什么吗?

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 documentation on parameters 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' }
});

Request in angular controller:角度控制器中的请求:

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

Your parameter format is not right你的参数格式不对

Replace your route with this用这个替换你的路线

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

Request#query请求#query

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

Request#param请求#param

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

Maybe it is too late, but for the ones who have this problem yet, it is not with the keyword this, but ctx.也许为时已晚,但对于那些还遇到这个问题的人来说,不是关键字this,而是ctx。 The following, when consulted with the url以下,当与url协商时

http://myweb.com/endpoint/45 http://myweb.com/endpoint/45

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

returns the following json:返回以下 json:

{ "id": "45"}

And this:和这个:

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

when consulted with the same url returns当使用相同的 url 进行咨询时返回

45

Edit: The good news is that the two endpoints are really different.编辑:好消息是这两个端点确实不同。 You can have the both endpoints and the router can decide between the two based on the url you type in your browser.您可以拥有两个端点,路由器可以根据您在浏览器中输入的 url 在两者之间做出决定。

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

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