ddesai
ddesai

Reputation: 519

Express Node JS

Following is my code as follows:

    var express = require('express');
var app = express();
var router = express.Router();

app.route('/')
  .get(function(req, res) {
    res.send('Hello World!');
  });

app.route('/user')
    .get(function (req, res) {
      res.send('Hello' + req.params.id);
});

var server = app.listen(8000, function () {
  var host = server.address().address;
  var port = server.address().port;
  console.log('Example app listening at http://%s:%s', host, port);
});

It runs fine with http://localhost:8000/ but with http://localhost:8000/user?id=D it gives following error: Cannot GET /user?id=D.

WHat is wrong in my code? Please help.

Thanks.

Upvotes: 0

Views: 46

Answers (1)

jfriend00
jfriend00

Reputation: 707148

This route syntax:

'/user/:id'

matches a URL like this:

http://localhost:8000/user/4095

If you use a URL like this:

http://localhost:8000/user?id=D

then, you will need to use a "/user" route and read the query parameter for the id value from req.query.id as described here.


In addition, your don't need the app.route() as it's just an extra level of complication for things you are not doing here. I'd suggest this simplification which I have tested and works:

var express = require('express');
var app = express();

app.get('/', function(req, res) {
    res.send('Hello World!');
  });

app.get('/user', function (req, res) {
    res.send('Hello: ' + req.query.id);
});

var server = app.listen(8000, function () {
  var host = server.address().address;
  var port = server.address().port;
  console.log('Example app listening at http://%s:%s', host, port);
});

Upvotes: 2

Related Questions