首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用koa-router获取请求参数

使用koa-router获取请求参数
EN

Stack Overflow用户
提问于 2016-09-08 18:15:39
回答 2查看 21.7K关注 0票数 8

http://localhost:3000/endpoint?id=83结果为404 (未找到)。所有其他路由都按预期工作。我是不是漏掉了什么?

代码语言:javascript
复制
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-有关参数的路由器文档

代码语言:javascript
复制
//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' }
});

角度控制器中的请求:

代码语言:javascript
复制
 $http.get('/endpoint', {params: { id: 223 }})
    .then(
      function(response){
        var respnse = response.data;
        console.log(response);
      }
  );
EN

回答 2

Stack Overflow用户

发布于 2016-09-08 18:24:56

您的参数格式不正确

将您的路径替换为以下内容

代码语言:javascript
复制
.get('/endpoint/:id', function *(next) {
    console.log(this.params);
    this.body = 'Endpoint return';
  })

Request#query

代码语言:javascript
复制
.get('/endpoint/', function *(next) {
    console.log(this.query);
    this.body = 'Endpoint return';
  })

Request#param

代码语言:javascript
复制
.get('/endpoint/:id', function *(next) {
    console.log(this.params);
    this.body = 'Endpoint return';
  })
票数 8
EN

Stack Overflow用户

发布于 2020-01-22 23:13:15

也许为时已晚,但对于那些还存在这个问题的人来说,关键字不是this,而是ctx。以下内容在与url一起查阅时提供

http://myweb.com/endpoint/45

代码语言:javascript
复制
 .get('/endpoint/:id', async (ctx, next) => {
     console.log(ctx.params);
     this.body = 'Endpoint return';   })

返回以下json:

代码语言:javascript
复制
{ "id": "45"}

还有这个:

代码语言:javascript
复制
 .get('/endpoint/:id', async (ctx, next) => {
     console.log(ctx.params.id);
     this.body = 'Endpoint return';   })

当使用相同的url查询时,返回

代码语言:javascript
复制
45

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

票数 6
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/39388287

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档