javascript expressjs 路由器不工作

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28196421/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 08:33:45  来源:igfitidea点击:

expressjs router not working

javascriptnode.jsexpress

提问by Iori

I am new to MEAN stack, so i am going through tutorials and it pretty clear that not all people use same logic. But now i am stuck on these two examples

我是 MEAN 堆栈的新手,所以我正在学习教程,很明显并非所有人都使用相同的逻辑。但现在我被困在这两个例子上

Example One

示例一

// server.js
var express = require('express'),
    app = express(),
    port = 1337;
// indicating view folder
app.set('views', './views');
// indicating view engine
app.set('view engine', 'ejs');
// adding routes
require('./routes/index.js')(app);
require('./routes/user.js')(app);
//
app.listen(port);
module.exports = app;


./routes/index.js
module.exports = function(app) {
    // show indix view
    app.get('/', function(req, res) {
            res.render('index', {
                title: 'Index page',
            });
    });
};

above we are using getmethod from app(which is instance of express)

上面我们使用的get方法来自app(这是 的实例express

./routes/user.js
module.exports = function(app) {
    // showing user page
    app.route('/users').get(function(req, res) {
            res.render('user', {
                title: 'User page'
            });
    });
};

above we are using routemethod of expressand then bind getto it

上面我们使用的route方法是express然后绑定get到它

so when the app is running, and i access localhost:1337index page is called and when localhost:1337/useris called user page is called

所以当应用程序运行时,我访问localhost:1337索引页面被调用,何时localhost:1337/user被调用用户页面被调用

Example two Now when we use express myappcommand, this example has some different logic

示例二 现在当我们使用express myapp命令时,这个示例有一些不同的逻辑

we have main app.js

我们有主要的 app.js

var express = require('express');

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

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

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

app.listen(1337);

module.exports = app;

As you can see first we require indexand userroute files required and then we use app.usecommand to set routes.

如您所见,首先我们需要indexuser路由所需的文件,然后我们使用app.use命令来设置路由。

in ./routes/index.jsfile

./routes/index.js文件中

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

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

module.exports = router;

we get method routerof expressand then bind getmethod to it

我们得到的方法routerexpress,然后绑定get方法将其

so my question is, when i commit app.use('/', routes);and call localhost:1337i get error but we have already using router in ./routes/index.jsto show index page. this should work according to first example.

所以我的问题是,当我提交app.use('/', routes);并调用时localhost:1337出现错误,但我们已经使用路由器./routes/index.js来显示索引页面。这应该根据第一个例子工作。

EDIT error msg

编辑错误消息

Error: Not Found
    at app.use.res.render.message (/home/vagrant/meanstack/myapp/app.js:30:15)
    at Layer.handle [as handle_request] (/home/vagrant/meanstack/myapp/node_modules/express/lib/router/layer.js:82:5)
    at trim_prefix (/home/vagrant/meanstack/myapp/node_modules/express/lib/router/index.js:302:13)
    at /home/vagrant/meanstack/myapp/node_modules/express/lib/router/index.js:270:7
    at Function.proto.process_params (/home/vagrant/meanstack/myapp/node_modules/express/lib/router/index.js:321:12)
    at next (/home/vagrant/meanstack/myapp/node_modules/express/lib/router/index.js:261:10)
    at SendStream.error (/home/vagrant/meanstack/myapp/node_modules/express/node_modules/serve-static/index.js:107:7)
    at SendStream.emit (events.js:95:17)
    at SendStream.error (/home/vagrant/meanstack/myapp/node_modules/express/node_modules/send/index.js:244:17)
    at SendStream.onStatError (/home/vagrant/meanstack/myapp/node_modules/express/node_modules/send/index.js:340:48)

i had this code to handle error

我有这个代码来处理错误

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

now when i comment this code and comment app.use('/', routes);and run the server.js

现在,当我评论此代码并评论 app.use('/', routes);并运行 server.js 时

i get this when i run localhost:1337

我跑步时得到这个 localhost:1337

Cannot GET / 

if you still cannot see the error, try express appin folder and create a new file server.jsand add below code and run node server.js

如果您仍然看不到错误,请尝试express app在文件夹中创建一个新文件server.js并添加以下代码并运行node server.js

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

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

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

app.listen(1337);

module.exports = app;
console.log(" call 192.168.33.33:1337");

回答by Yuri Zarubin

I ran express-generator, created a new file server.js with the code you provided. Upon hitting my localhost:1337 I got a 'CANNOT GET /' error. I then uncommented this line inside server.js

我运行了 express-generator,使用您提供的代码创建了一个新文件 server.js。在点击我的 localhost:1337 后,我收到了“无法获取 /”错误。然后我在 server.js 中取消注释这一行

app.use('/', routes);

And it worked.

它奏效了。

EDIT:

编辑:

The reason why you need to call app.use('/', routes) for the route handling to work is because when you call

您需要调用 app.use('/', routes) 以使路由处理工作的原因是因为当您调用

var app = express();

At this point, the 'app' variable contains a reference to your express object in memory. Meaning when you call

此时,“app”变量包含对内存中 express 对象的引用。当你打电话时的意思

var router = express.Router(); 

Router at this point is standalone object. Router has no reference to the app you created, meaning when you register your GET route with route.get(), it does not affect your app instance of express. Hence when you hit localhost:1337, you get an error until you register the route.

此时的路由器是独立的对象。Router 没有引用您创建的应用程序,这意味着当您使用 route.get() 注册您的 GET 路由时,它不会影响您的 express 应用程序实例。因此,当您点击 localhost:1337 时,您会收到一个错误,直到您注册该路由。

In order to register your router with your app, you need to export and require your router, and register it with

为了在您的应用程序中注册您的路由器,您需要导出并要求您的路由器,并将其注册

routes = require('path/to/router')
app.use('/', routes)

The reason why your first example worked, is because in that case, you were registering the route handler directly with your app instance, using app.get()

您的第一个示例之所以有效,是因为在这种情况下,您使用 app.get() 直接向应用程序实例注册了路由处理程序