简体   繁体   中英

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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