Express路由器不工作

时间:2017-09-08 17:49:33

标签: node.js express

我是新手来表达和使用yo-generator来创建我的项目。我面临的问题是路线:

app.get('/ something')工作正常,但

router.get('/ something')无效。我试图研究,但无法解决问题。 这是我的文件:

app.js

var fs = require('fs');
var http = require('http');
var path = require('path');
var helmet = require('helmet');
var express = require('express');
var root = path.normalize(__dirname + '/');
var constant = require(root + '/app/util/constants.js');

var config = require(constant.APP_CONFIG_FILE);

var app = express();
app.use(helmet());

app.use(function(req, res, next) {
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader("Access-Control-Allow-Headers", "DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type");
return next();
});

require('./config/express')(app, config);

http.createServer(app).listen(config.WEB_PORT, function() {
console.log('Server listening http on port ' + config.WEB_PORT);
});

module.exports = app;

来自 express.js

的行
var env = process.env.NODE_ENV || 'development';
app.locals.ENV = env;
app.locals.ENV_DEVELOPMENT = env == 'development';

app.set('views', config.ROOT + '/app/views');
app.set('view engine', 'ejs');

// app.use(favicon(config.root + '/public/img/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
    extended: true
}));
app.use(cookieParser());
app.use(compress());
app.use(express.static(config.ROOT + '/public'));
app.use(methodOverride());

var controllers = glob.sync(config.ROOT + '/app/controllers/*.js');
controllers.forEach(function(controller) {
    require(controller)(app);
});

app.use(function(req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    next(err);
});

应用/控制器/用户ctrl.js

var path = require('path');
var express = require('express');

var router = express.Router();
var root = path.normalize(__dirname + '/../..');
var constant = require(root + '/app/util/constants.js');

var service = require(constant.USER_SERVICE_FILE);
var responseUtil = require(constant.RESPONSE_UTIL_FILE);

module.exports = function(app) {
app.use(constant.USER_PATH, router);   // constant.USER_PATH is '/user' (added after alexmac asked)

**// this works**
app.get('/test', function(req, res) {
    res.write('hello');
    res.end();
});

**// This doesn't work**
router.get('/test', function(req, res) {
    res.write('hello');
    res.end();
});

};


/* 
GET: /user
*/
router.route('/:page?/limit?/:limit')
.get(function(req, res) {
    responseUtil.sendResponse(service.allRecords(req, res), req, res);
});

/* 
POST: /user
*/
router.route('/')
.post(function(req, res) {
    responseUtil.sendResponse(service.saveRecord(req, res), req, res);
});

/* 
GET: /user/1
PUT: /user/1
DELETE: /user/1
*/
router.route('/:id')
.get(function(req, res) {
    responseUtil.sendResponse(service.findRecord(req, res), req, res);
})
.delete(function(req, res) {
    responseUtil.sendResponse(service.deleteRecord(req, res), req, res);
})
.put(function(req, res) {
    responseUtil.sendResponse(service.updateRecord(req, res), req, res);
});

2 个答案:

答案 0 :(得分:3)

这些是关键路线。我已经改变了命令,试图澄清意图,但这不应该改变他们的行为方式:

// Create a route for GET /test
app.get('/test', function(req, res) {
    res.write('hello');
    res.end();
});

// Create a route for GET /user/test
router.get('/test', function(req, res) {
    res.write('hello');
    res.end();
});

app.use('/user', router);

router已安装在路径/user上,因此router上的所有路径都将相对于/user。换句话说,如果app正在http://localhost/test处理请求,那么router将处理http://localhost/user/test

答案 1 :(得分:1)

使用这段代码更改您的代码

var express = require('express');
var bodyParser = require('body-parser');
var router = express.Router();
router.use(bodyParser.json());
var app = express();
router.get('/test', function(req, res) {
    res.write('hello');
    res.end();
});

app.use('/route',router);

module.exports = router;

如果您想使用http://localhost:port/route/test

希望这有帮助。