Node.js url route formatting

节点。js url路径格式

问题 (Question)

I am coding a REST API using restiy node.js.

Right now I am doing like this:

"http://test.com/products/query/keyword"  

Routing = server.get('products/query/:keyword', myCallBack);

And getting the params like req.pramams.keyword

I want to get params like :

"http://test.com/products/?query=keyword"
 Routing ?

Thanks in advance.

我是编码一个REST API使用restiy node . js。

现在我正在做这样的:

"http://test.com/products/query/keyword"  

Routing = server.get('products/query/:keyword', myCallBack);

和等参数req.pramams.keyword

我想要参数:

"http://test.com/products/?query=keyword"
 Routing ?

提前谢谢。

最佳答案 (Best Answer)

You can use the req.query object:

// if you use Express (as your tags seem to suggest)
var express = require('express');
var app     = express();

app.get('/products/', function(req, res) {
  res.send('Query sent: ' + req.query.query);
});

app.listen(3012);
// if you use Restify (as your text seems to suggest)
var restify = require('restify');
var app     = restify.createServer();

app.pre(restify.pre.sanitizePath()); // necessary to be able to use /products/
                                     // (with trailing slash)
app.use(restify.queryParser());

app.get('/products/', function(req, res) {
  res.send(req.query.query);
});

app.listen(3012);

您可以使用req.query对象:

// if you use Express (as your tags seem to suggest)

本文翻译自StackoverFlow,英语好的童鞋可直接参考原文:http://stackoverflow.com/questions/16925923