使用koa-router获取请求参数

Out*_*bit 4 parameters get node.js koa 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';
  })
Run Code Online (Sandbox Code Playgroud)

有关参数的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' }
});
Run Code Online (Sandbox Code Playgroud)

请求角度控制器:

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

abd*_*rik 8

您的参数格式不正确

用这个替换你的路线

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

请求#查询

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

请求#PARAM

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


Eri*_*ric 6

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

http://myweb.com/endpoint/45

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

返回以下 json:

{ "id": "45"}
Run Code Online (Sandbox Code Playgroud)

和这个:

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

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

45
Run Code Online (Sandbox Code Playgroud)

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