404使用nginx和expressjs进行路由

时间:2015-09-13 09:09:13

标签: node.js express nginx amazon-ec2 express-generator

我在EC2上创建了一个ubuntu服务器的实例,并尝试让快速生成器简单的骨架开始工作。
当我转到根http://MY_SERVER_IP_HERE/时,会显示应用程序的索引页面 如果我去http://MY_SERVER_IP_HERE/users即时获得404,即使快递应用程序设置为处理此路线。

var routes = require('./routes/index');
var users = require('./routes/users');

app.use('/', routes);
app.use('/users', users);

/routes/index.js

var express = require('express');
var router = express.Router();

/* GET home page. */
/**** WORKS FINE ****/
router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });
});

module.exports = router;

/routes/users.js

var express = require('express');
var router = express.Router();

/* GET users listing. */
/*** GETTING 404 ****/
router.get('/', function(req, res, next) {
  res.send('respond with a resource');
});

module.exports = router;

我的nginx路由设置:

location ~ ^/(stylesheets/|css/|js/){
    root /var/www/html/test/myapp/public;
}

location / {
    proxy_pass http://MY_SERVER_IP:3000;
}
非常感谢你!

1 个答案:

答案 0 :(得分:0)

像这样更改代码。

<强> server.js

var express= require('express');
var app = express();  
require('./routes/index')(app, express);
require('./routes/users')(app, express);
//.....
app.listen(3000);

<强> /routes/index.js

module.exports  = function(app, express) {
    var router = express.Router();
    router.get('/', function(req, res, next) {
        res.render('index', { title: 'Express' });
    });
    app.use('/', router);
};

<强> /routes/users.js

module.exports  = function(app, express) {
    var router = express.Router();
    router.get('/', function(req, res, next) {
        res.send('respond with a resource');
    });
    app.use('/users', router);
};