在我的应用程序中,我有3条路径
http://localhost:8080/search
http://localhost:8080/user
http://localhost:8080/shop
我在server.js(终端中运行的文件)的分隔文件中写路由:
app.use('/', require('./app/routes/index')(app,io,mongoose));
在index.js中:
app.use('/search', require('./searchRouter')(router));
app.use('/user', require('./user')(router,io,mongoose,app,express));
app.use('/shop', require('./shop')(router,io,mongoose,app,express));
他们都有一条路线:
router.route('/')
.get(function(req, res) {
res.send('routerRestuarant');
})
.post(function(req, res) {
res.send('routerRestuarant');
})
.put(function(req,res){
res.json({
msg:"new shop.js router"
})
});
问题:
当我向路线' / shop'发送请求时,我发现回复来自' / search'没有回应来自' / shop',如何解决?
关于传递 mongoose,app,express 变量
我的代码的一部分如下:
Index.js:
var express = require('express');
//var router = express.Router({ mergeParams: true });
var router = express.Router();
var routeInit = function (app,io,mongoose) {
//app.use('sessions', require('./sessions')(router));
app.use('/test', require('./searchRouter')(router));
app.use('/user', require('./user')(router,io,mongoose,app,express));
app.use('/shop', require('./shop')(router,io,mongoose,app,express));
return router;
};
module.exports = routeInit;
Shop.js:
var routeShop = function (router,io,mongoose,app,express) {
var Shop = require('../models/Shop')(mongoose);
router.route('/createDish')
.post(function(req, res) {
var dish = req.param('dish', null);
var shopName = req.param('shopName', null);
for (var i = 0; i < dish.length; i++) {
Shop.addDish(shopName, dish[i], function(err) {
if (null == err)
res.json({
code: 200
});
})
}
})
return router;
};
module.exports = routeShop;
在Shop.js中,我需要变量mongoose来初始化mongoose模式,如果我没有在这里传递变量mongoose,则编译器错误是:
/Users/Documents/Dropbox/MScCS/fos/app/routes/shop.js:8
var Shop = require('../models/Shop')(mongoose);
^
ReferenceError: mongoose is not defined
at routeShop (/Users/liyan/Documents/Dropbox/MScCS/fos/food-ordering-by-zwy-liyan/food-ordering/app/routes/shop.js:8:38)
答案 0 :(得分:3)
尝试这种方式:
在server.js中:
// defining components to be accessible from route handlers
app.use(function(req, res, next) {
req.components = {
io: io,
mongo: mongoose
};
next();
});
app.use(require('./app/routes/index'));
index.js中的:
var
express = require('express'),
router = express.Router();
router.use('/search', require('./searchRouter'));
router.use('/user', require('./user'));
router.use('/shop', require('./shop'));
module.exports = router;
路由器文件中的:
var
express = require('express'),
router = express.Router();
router.get('/', function(req, res) {
req.components.io.emit('message', {data: "I'm in restaurant"});
res.send('routerRestuarant');
});
router.post('/', function(req, res) {
res.send('routerRestuarant');
})
router.put('/', function(req,res){
res.json({
msg:"new shop.js router"
});
});
module.exports = router;