首页 > 解决方案 > 快递路线问题

问题描述

我对表达非常陌生,并且在设置正确的路由时遇到了问题。这是一个家庭作业,所以路由器文件已经写好了,但是我们应该填写一个 express.js 文件,以便在该地址发出 get/put/post/delete 请求时调用 api。路由器文件是这样设置的:

var listings = require('../controllers/listings.server.controller.js'), 
    getCoordinates = require('../controllers/coordinates.server.controller.js'),
    express = require('express'), 
    router = express.Router();

/* 
  These method calls are responsible for routing requests to the correct request handler.
  Take note that it is possible for different controller functions to handle requests to the same route.
 */
router.route('/')
  .get(listings.list)
  .post(getCoordinates, listings.create);

/*
  The ':' specifies a URL parameter. 
 */
router.route('/:listingsId')
  .get(listings.read)
  .put(getCoordinates, listings.update)
  .delete(listings.delete);

/*
  The 'router.param' method allows us to specify middleware we would like to use to handle 
  requests with a parameter.

  Say we make an example request to '/listings/566372f4d11de3498e2941c9'

  The request handler will first find the specific listing using this 'listingsById' 
  middleware function by doing a lookup to ID '566372f4d11de3498e2941c9' in the Mongo database, 
  and bind this listing to the request object.

  It will then pass control to the routing function specified above, where it will either 
  get, update, or delete that specific listing (depending on the HTTP verb specified)
 */
router.param('listingId', listings.listingByID);

module.exports = router;

express.js 文件是这样的:

var path = require('path'),  
    express = require('express'), 
    mongoose = require('mongoose'),
    morgan = require('morgan'),
    bodyParser = require('body-parser'),
    config = require('./config'),
    listingsRouter = require('../routes/listings.server.routes'), 
    getCoordinates = require('../controllers/coordinates.server.controller.js');

module.exports.init = function() {
  //connect to database
  mongoose.connect(config.db.uri, {useMongoClient: true});

  //initialize app
  var app = express();

  //enable request logging for development debugging
  app.use(morgan('dev'));

  //body parsing middleware 
  app.use(bodyParser.json());

  /* server wrapper around Google Maps API to get latitude + longitude coordinates from address */
  app.post('/api/coordinates', getCoordinates, function(req, res) {
    res.send(req.results);
  });

  This is the part I can't figure out:
  /* serve static files */
  app.get('/listings', listingsRouter, function(req, res){
    res.send(req.get('/'))
  });

  /* use the listings router for requests to the api */


  /* go to homepage for all routes not specified */ 

  return app;
};  

我只是不确定如何将 ListingsRouter 文件中的路由与 req 和 res 对象一起使用,而且我找不到任何像这样设置的程序示例来提供帮助。任何援助将不胜感激。

标签: node.jsexpressmongoosegetrouting

解决方案


更改以下

app.get('/listings', listingsRouter, function(req, res){
    res.send(req.get('/'))
});

app.use('/listings', listingsRouter);

快速路由器。向下滚动到express.Router部分以获取完整信息。

希望这有帮助。


推荐阅读