简体   繁体   中英

Node express.Router().route(/verb/:optionalParameter)?

I use node express Router module, and it's route() method.

I need to accept an optional parameter, this way:

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

router.route('/verb/:optionalParameter').get(function(req, res, next) {
  // ...
}

How do I specify optionalParameter ?
I did try:

router.route('/verb/:optionalParameter*?').get(function(req, res, next) {

and

curl -X GET -H "Accept: application/json" http://localhost:3000/verb/option1

works just fine, but

curl -X GET -H "Accept: application/json" http://localhost:3000/verb

spits a 404...

I'm sure I'm missing something obvious... :-( Any clue?

Response it's 404 because don't exist route /verb , only /verb/:optionalParameter .

For works, it's need to create another route:

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

router.route('/verb/:optionalParameter').get(function(req, res, next) {
  // ...
}

// route localhost:3000/verb
router.route('/verb').get(function(req, res, next) {
  // ...
}

And try:

curl -X GET -H "Accept: application/json" http://localhost:3000/verb

Try this instead:

var express = require('express')
var router = express.Router()
var app = express()
app.route('/verb/:optionalParameter?').get(function(req, res, next) { console.log('hello world') })

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