node.js – 使用搜索参数快速路由GET

前端之家收集整理的这篇文章主要介绍了node.js – 使用搜索参数快速路由GET前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有两条获取商店的GET路线,但是,一条路线用于获取所有商店,另一条路线用于获取附近的商店.

1)获取所有商店的网址请求如下:

http://mydomain/stores

2)获取附近所有商店的网址:

http://mydomain/stores?lat={lat}&lng={lng}&radius={radius}

问题是:

如何在Express中正确映射这些URL,以便将每个路由重定向到相应的方法

app.get('/stores',store.getAll);

app.get('/stores',store.getNear);

解决方法

app.get('/stores',function(req,res,next){
  if(req.query['lat'] && req.query['lng'] && req.query['radius']){
    store.getNear(req,next);
  } else {
    store.getAll(req,next)
  };
});

编辑 – 第二种方式:

store.getNear = function(req,next){
  if(req.query['lat'] && req.query['lng'] && req.query['radius']){
    // do whatever it is you usually do in getNear
  } else {  // proceed to the next matching routing function
    next()
  };
}
store.getAll = function(req,next){
  // do whatever you usually do in getAll
}

app.get('/stores',store.getNear,store.getAll)
// equivalent:
// app.get('/stores',store.getNear)
// app.get('/stores',store.getAll)

猜你在找的Node.js相关文章