简体   繁体   中英

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.

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

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