简体   繁体   中英

Named arguments in routing in Express.js

I can't seem to find information about this anywhere.

I want to be able to do requests like this: url/list/message=hello?id=1234

But like I've said, I haven't been able to find any information on how to do this in Express.

My initial guess was to do this:

app.put('/list/message=:msg?id=:id', function (req, res) { ... });

But this doesn't quite work. Is there any way to do this at all in Express?

What you're referring to is generally called a query string , and we have a powerful URL parsing library in node to handle that for us.

Try this:

require('url');
...
var url_parts = url.parse(req.url, true);
var query = url_parts.query;

Then, you can use query.id and get 1234 , IF you change your route to this:

app.put('/list/message=:msg', function (req, res) { ... });

Ideally, you should check that query.id exists before attempting to read from it. I would also recommend against using an message=:msg . Instead, I would rewrite the whole thing as

app.put('/list/:id', function (req, res) {
  var url_parts = url.parse(req.url, true);
  var query = url_parts.query;
  if (query.message) {...}
});

which is a slightly different structure than you have currently, but is more in line with how a great deal of APIs handle their routing.

You can't do it like that. What you can do is:

app.put('/list/message/:msg', function (req, res) {
  var msg = req.params.msg;

  var url = require('url');
  var id = url.parse(req.url, true).query.id;    
});

Your URL will look like this: url/list/message/hello?id=1234

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