微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

node.js – 向node express添加新路由

我试图在我的快速应用程序中添加一个新路由,但是当尝试启动服务器时,我会收到错误.错误

C:\development\node\express_app\node_modules\express\lib\router\index.js:252
    throw new Error(msg);
          ^
Error: .get() requires callback functions but got a [object Undefined]

这是我的文件,我是新的节点,所以让我知道,如果我省略了一个重要的文件

路线/ furniture.js

exports.furniture = function(req,res){
   res.render('furniture',{ title: '4\267pli' });
};

路线/ index.js

/*
 * GET home page.
 */

exports.index = function(req,res){
  res.render('index',{ title: '4\267pli' });
};

意见/ furniture.ejs

<!DOCTYPE html>
<html>
<head>
    <title>4&middot;pli -- architecture</title>
    <link rel='stylesheet' href='/stylesheets/style.css'/>
    <link href='http://fonts.googleapis.com/css?family=Didact+Gothic' rel='stylesheet' type='text/css'>
</head>
<body>
<div class="wrapper">
    <h1 class="logo"><%= title %></h1>
</div>
</body>
</html>

app.js

/**
 * Module dependencies.
 */

var express = require('express'),routes = require('./routes'),user = require('./routes/user'),furniture = require('./routes/furniture'),http = require('http'),path = require('path');

var app = express();

// all environments
app.set('port',process.env.PORT || 3000);
app.set('views',__dirname + '/views');
app.set('view engine','ejs');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodoverride());
app.use(app.router);
  app.use(require('stylus').middleware(__dirname + '/public'));
app.use(express.static(path.join(__dirname,'public')));

// development only
if ('development' == app.get('env')) {
  app.use(express.errorHandler());
}

app.get('/',routes.index);
app.get('/users',user.list);
app.get('/furniture',routes.furniture);

http.createServer(app).listen(app.get('port'),function(){
  console.log('Express server listening on port ' + app.get('port'));
});

解决方法

麻烦是:

routes = require('./routes'),

这3个都设置你的路由文件夹,而不是一个特定的文件,express将会找到一个index.js(找不到,然后是>错误)

在这文件夹里面,你应该把一个index.js与你的

exports.xxxx =  function(req,res){
    res.render('xx',{ foo: foo);
};

然后,您的项目文件夹结构应如下所示:

routes/
  ├── index.js
  │
  ├── user/
  │     └── index.js (with a exports.user inside)
  │   
  └── fourniture/
        └── index.js (with a exports.furniture inside)

您可以添加多个导出功能到这样的路由:

app.js

// a folder called routes with the index.js file inside
routes = require('./routes')

.
.
.

app.get('/',routes.main_function);  
app.get('/sec_route',routes.sec_function);
app.post('/other_route',routes.other_function);

/routes/index.js

exports.main_function =  function(req,res){
    res.render('template1',{ foo: foo });
};

exports.sec_function =  function(req,res){
    res.render('template2',{ bar: bar });
};

exports.other_function =  function(req,{ baz: baz });
};

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐