Express Generator 生成Express應(yīng)用的目錄結(jié)構(gòu)

這是我的MDN Express Tutorial 學(xué)習(xí)摘錄。在那篇教程里,Express 的主要功能都有涉及到,講的很全面。親自動手操練一遍,會加深對 express 的認(rèn)識。

這篇文章主要介紹 express generator 的使用,以及使用它生成 express 應(yīng)用的目錄結(jié)構(gòu)。

Node 和 Express

Node是目前最厲害、最流行的平臺,可以使用JavaScript開發(fā)后端應(yīng)用。

Express是2010年出來的最流行的Node應(yīng)用框架。

Node (or more formally Node.js) is an open-source, cross-platform, runtime environment that allows developers to create all kinds of server-side tools and applications in JavaScript.

Express](https://expressjs.com/) is the most popular Node web framework, and is the underlying library for a number of other popular Node web frameworks.

沒吃到豬肉前,先來看看豬是怎么跑的。這篇文章帶你快速瀏覽Express應(yīng)用:What does Express code look like?

使用 Express Generator

Express Application Generator 能夠快速創(chuàng)建一個Express應(yīng)用框架。

npm install express-generator -g
express myapp --view=pug
cd myapp
npm install

# Run the myapp on Windows
SET DEBUG=myapp:* & npm start

# Run myapp on Linux/Mac OS X
DEBUG=myapp:* npm start

http://localhost:3000/ 看看剛才創(chuàng)建的Express應(yīng)用長什么樣。

添加nodemon

在開發(fā)的時候,每次修改文件,都需要重啟 express 服務(wù),比較麻煩。使用nodemon,修改文件后可以自動重啟 express 服務(wù)。

npm install --save-dev nodemon

修改 package.json 的 scripts 內(nèi)容:

"scripts": {
    "start": "node ./bin/www",
    "devstart": "nodemon ./bin/www"
  }

之后,使用 SET DEBUG=myapp:* & npm run devstart 啟動 express 服務(wù)。這樣在開發(fā)過程中修改文件的時候,express服務(wù)就會自動重啟,非常方便。

生成的文檔目錄結(jié)構(gòu)

/myapp
    app.js
    /bin
        www
    package.json
    /node_modules
        [about 4,500 subdirectories and files]
    /public
        /images
        /javascripts
        /stylesheets
            style.css
    /routes
        index.js
        users.js
    /views
        error.pug
        index.pug
        layout.pug

www file

/bin/www 是應(yīng)用的主入口。應(yīng)用的真正入口是app.js文件,所以www文件先把app.js文件引進來,其余的內(nèi)容主要就是創(chuàng)建了一個node HTTP server。

app.js

這個可是主要文件,得好好嘮嘮,在app.js里面,主要做了這些事兒:

1.引入之前使用npm install下載的包,并創(chuàng)建express對象:

var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

var app = express();

2.使用上面引入的包:

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

3.引入routes文件夾里面的文件,這些文件主要處理URL路由。

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

4.關(guān)聯(lián)路由路徑與引入的文件:

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

5.設(shè)置模板,views 設(shè)置了模板的位置;view engine設(shè)置了要使用的模板引擎。

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

6.最后處理錯誤的http請求:

// 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 handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

routes文件夾

以users.js為例,首先加載express,通過express獲取到router對象。使用router對象指定路由的方法和路徑。由于在app.js已經(jīng)指定 /users 到本文件,因此當(dāng)瀏覽器請求/user時,會執(zhí)行下面的回調(diào)函數(shù)。

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

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

module.exports = router;

回調(diào)函數(shù)有第三個參數(shù)next,主要用于中間件中,即將數(shù)據(jù)傳遞到下一個方法去處理。

視圖模板

A template engine enables you to use static template files in your application. At runtime, the template engine replaces variables in a template file with actual values, and transforms the template into an HTML file sent to the client. This approach makes it easier to design an HTML page.

Express 應(yīng)用默認(rèn)使用的是 pug 模板,views文件里面是所有的視圖模板。在router文件里, 使用Response.render()指定要加載的模板和傳遞給模板的一些參數(shù)。下面的/routes/index.js文件里的示例:

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

下面是index.pug文件,傳進來的title的值將替換它:

extends layout

block content
  h1= title
  p Welcome to #{title}

好了,Express Generator生成的文件就是這樣了,接下來,就開始Express應(yīng)用的開發(fā)吧!

另外Express官網(wǎng)的文檔寫的不錯,有問題就找它。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容