简体   繁体   English

使用快递node.js的路由但表达。路由器获取未定义

[英]Using Route of express node.js but express.Router getting as undefined

My code of router from default routes/index 我的路由器代码来自默认路由/索引

/* GET home page. */
exports.index = function(req, res){
  res.render('user', { title: 'Abcd' });
};

var express = require('express');

var router = express.Router();

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

router.get('/helloworld', function(req, res) {
    res.render('helloworld', { title: 'Hello, World!' })
});

module.exports = router;

getting error as can not call method get of undefined.I am new in node js please anyone help me. 得到错误,因为无法调用方法得到undefined。我是节点js的新人,请任何人帮助我。

Try upgrading to Express 4.x. 尝试升级到Express 4.x. You are probably running a 3.x flavor. 你可能正在运行3.x风味。

Router is a middleware of express which is registered implicitly with the express object the first time post() or get() is used. 路由器是express的中间件 ,它在第一次使用post()get()时与express对象隐式注册。 You can but don't have to add this explicitly calling use() , which allows you to register various middleware with express and so allows configuring processing and behavior in consideration of precedence. 您可以但不必添加此显式调用use() ,它允许您使用express注册各种中间件,因此允许在考虑优先级的情况下配置处理和行为。

Correct initialization and usage might look like this: 正确的初始化和使用可能如下所示:

EDIT : Changed the example to be a "complete" http server. 编辑 :将示例更改为“完整”的http服务器。

app.js app.js

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

// Requiring express exports a function that creates the application. Call it!
var app = express();

// Set port to listen to
app.set('port', process.env.PORT || 3000);

// Set view engine
app.set('view engine', 'jade');

// Tell express to use the router middleware
// Can be omitted if precedence doesn't matter 
// (e.g. for loading static resources)
app.use(app.router);

// Add callback handler for home (/) route
app.get('/', function(req, res) {
  res.render('index', { title: 'Express' });
});

// Create http server by passing "app" to it:
http.createServer(app).listen(app.get('port'), function() {
  console.log('Express server listening on port ' + app.get('port'));
});

Now, if you place a minimal view into the default folder for views... 现在,如果您将最小视图放入视图的默认文件夹中...

views/index.jade 意见/ index.jade

doctype 5
html
  head
    meta(charset='utf-8')
    title #{title}
    meta(name='viewport', content='width=device-width, initial-scale=1.0')
  body
    div
      h1 Gotcha! Title is "#{title}"

... and start your server from the console with... ...并从控制台启动服务器...

$ node app.js

...you should have your first node/express/jade powered app up and running! ...你应该启动并运行你的第一个节点/ express / jade应用程序!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM