Nodejs express 4.0x 使用ejs模版,生成的app.js没有app.configure,怎么弄?

Nodejs express 4.0x 使用ejs模版,生成的app.js没有app.configure,怎么弄?

express 4.0x 用ejs模版,生成的app.js没有app.configure,怎么弄?

5 回复

Nodejs Express 4.x 使用 EJS 模板时 app.configure 不可用怎么办?

在 Express 4.x 版本中,app.configure 方法已被移除。因此,在新版本中配置应用的方式有所不同。本文将介绍如何在 Express 4.x 中使用 EJS 模板引擎,并配置中间件和其他设置。

示例代码

首先,确保你已经安装了必要的依赖项:

npm install express ejs --save

然后,创建一个简单的 Express 应用程序,并使用 EJS 模板引擎。

// app.js
const express = require('express');
const path = require('path');

const app = express();

// 设置模板引擎为 EJS
app.set('view engine', 'ejs');

// 设置 views 文件夹的位置
app.set('views', path.join(__dirname, 'views'));

// 静态文件服务
app.use(express.static(path.join(__dirname, 'public')));

// 使用 body-parser 中间件
const bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

// 路由配置
app.get('/', (req, res) => {
    res.render('index', { title: 'Home Page' });
});

app.listen(3000, () => {
    console.log('Server is running on port 3000');
});

解释

  1. 设置模板引擎

    • app.set('view engine', 'ejs'):指定默认的视图引擎为 EJS。
    • app.set('views', path.join(__dirname, 'views')):指定 EJS 视图文件的存放路径。
  2. 静态文件服务

    • app.use(express.static(path.join(__dirname, 'public'))): 将 public 文件夹中的静态资源(如 CSS、JavaScript 和图片)暴露给客户端访问。
  3. 中间件

    • body-parser 中间件用于解析请求体中的 JSON 或 URL 编码数据。
    • app.use(bodyParser.json())app.use(bodyParser.urlencoded({ extended: false })) 分别用于处理 JSON 和 URL 编码的数据。
  4. 路由

    • app.get('/', ...) 定义了一个 GET 请求的路由,它会渲染 index.ejs 模板并传递一些数据到模板中。

通过这种方式,你可以轻松地在 Express 4.x 中配置和使用 EJS 模板引擎。不再需要使用 app.configure 方法,而是直接在代码中进行配置。


app.configure([env], callback) 当 env 和 app.get(‘env’)(也就是 process.env.NODE_ENV) 匹配时, 调用callback。保留这个方法是出于历史原因,后面列出的if语句的代码其实更加高效、直接。使用app.set()配合其它一些配置方法后,没有必要再使用这个方法。

// 所有环境 app.configure(function(){ app.set(‘title’, ‘My Application’); })

// 开发环境 app.configure(‘development’, function(){ app.set(‘db uri’, ‘localhost/dev’); })

// 只用于生产环境 app.configure(‘production’, function(){ app.set(‘db uri’, ‘n.n.n.n/prod’); })

更高效且直接的代码如下: // 所有环境 app.set(‘title’, ‘My Application’);

// 只用于开发环境 if (‘development’ == app.get(‘env’)) { app.set(‘db uri’, ‘localhost/dev’); }

// 只用于生产环境 if (‘production’ == app.get(‘env’)) { app.set(‘db uri’, ‘n.n.n.n/prod’); }

感谢!

请参考我的文章“使用express4.x版和Jade模板重写《nodejs开发指南》微博实例 ” 我使用express4写的app.js var express = require(‘express’); var path = require(‘path’); var favicon = require(‘static-favicon’); var logger = require(‘morgan’); var cookieParser = require(‘cookie-parser’); var bodyParser = require(‘body-parser’); //var partials = require(‘express-partials’);用jade模板,不能使用这个中间件 var session = require(‘express-session’); var MongoStore = require(‘connect-mongo’)(session); var settings = require(’./settings’); var flash = require(‘connect-flash’); 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(partials());

app.use(favicon()); app.use(logger(‘dev’)); app.use(bodyParser.json()); app.use(bodyParser.urlencoded());

//cookie解析的中间件 app.use(cookieParser()); app.use(express.static(path.join(__dirname, ‘public’))); app.use(flash());

//提供session支持 app.use(session({ secret: settings.cookieSecret, store: new MongoStore({ db: settings.db, }) }));

app.use(function(req, res, next){ console.log(“app.usr local”); res.locals.user = req.session.user; res.locals.post = req.session.post; var error = req.flash(‘error’); res.locals.error = error.length ? error : null;

var success = req.flash(‘success’); res.locals.success = success.length ? success : null; next(); });

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

/// catch 404 and forward to error handler app.use(function(req, res, next) { var err = new Error(‘Not Found’); err.status = 404; next(err); });

/// error handlers

// development error handler // will print stacktrace if (app.get(‘env’) === ‘development’) { app.use(function(err, req, res, next) { res.status(err.status || 500); res.render(‘error’, { message: err.message, error: err }); }); }

// production error handler // no stacktraces leaked to user app.use(function(err, req, res, next) { res.status(err.status || 500); res.render(‘error’, { message: err.message, error: {} }); }); module.exports = app;

在Express 4.x版本中,app.configure 方法已经被移除。取而代之的是直接在应用中设置中间件和配置。下面是具体步骤和示例代码,以帮助你在Express 4.x中使用EJS模板。

示例代码

  1. 安装必要的依赖
npm install express ejs
  1. 创建 app.js 文件
const express = require('express');
const path = require('path');

const app = express();

// 设置模板引擎为 EJS
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

// 设置静态文件目录
app.use(express.static(path.join(__dirname, 'public')));

// 使用 body-parser 中间件处理 POST 请求的数据
const bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

// 路由示例
app.get('/', (req, res) => {
    res.render('index', { title: 'Home Page' });
});

app.get('/about', (req, res) => {
    res.render('about', { title: 'About Page' });
});

// 启动服务器
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
    console.log(`Server is running on port ${PORT}`);
});

解释

  • 设置视图引擎:使用 app.set('view engine', 'ejs') 将EJS设置为默认视图引擎。

  • 设置视图目录:使用 app.set('views', path.join(__dirname, 'views')) 指定包含EJS模板的目录。

  • 中间件:在Express 4.x中,你可以直接添加中间件,如 body-parser 来解析请求体。

  • 路由:定义了两个简单的GET路由 //about,分别渲染 index.ejsabout.ejs 模板。

  • 启动服务器:最后,使用 app.listen 方法启动服务器。

以上步骤可以帮助你在Express 4.x中使用EJS模板,并且不需要使用已弃用的 app.configure 方法。

回到顶部