Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GET request parameters with koa-router

http://localhost:3000/endpoint?id=83 results in 404 (Not Found). 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

//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);
      }
  );
like image 462
Out of Orbit Avatar asked Sep 08 '16 10:09

Out of Orbit


2 Answers

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

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

Request#param

.get('/endpoint/:id', function *(next) {
    console.log(this.params);
    this.body = 'Endpoint return';
  })
like image 97
abdulbarik Avatar answered Nov 16 '22 22:11

abdulbarik


Maybe it is too late, but for the ones who have this problem yet, it is not with the keyword this, but ctx. The following, when consulted with the url

http://myweb.com/endpoint/45

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

returns the following 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

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.

like image 7
Eric Avatar answered Nov 16 '22 20:11

Eric