【问题标题】:GET request parameters with koa-router使用 koa-router 获取请求参数
【发布时间】:2017-01-16 05:31:12
【问题描述】:

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);
      }
  );

【问题讨论】:

    标签: node.js parameters get koa koa-router


    【解决方案1】:

    你的参数格式不对

    用这个替换你的路线

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

    请求#查询

    .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';
      })
    

    【讨论】:

    • 不工作我害怕。添加两条路由(Request#query 和 Request#param)只为“查询”提供服务,无论我在请求中是否有参数。仅定义“.get('/endpoint/:id', funtion...”返回 404
    • 你能从你请求的地方发布你的代码吗?
    • 在问题中添加了角度 $http 请求。也只是使用浏览器 url 来测试
    • 意思是你在做 get('/arrow/:id', function *(next) {}?
    • 这样做 get('/endpoint', function *(next) { 并检查 console.log(this.params || this.request.params)
    【解决方案2】:

    也许为时已晚,但对于那些还有这个问题的人来说,不是关键字this,而是ctx。以下,当咨询网址时

    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 在两者之间做出决定。

    【讨论】:

      猜你喜欢
      • 2015-10-08
      • 1970-01-01
      • 1970-01-01
      • 2017-02-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-09
      • 1970-01-01
      • 2018-05-30
      相关资源
      最近更新 更多