什么是express
express是一个基于node.js平台的,快速、极简web开发框架。
第一个express程序hello world
- 创建工程目录hello-express, 并使用npm init命令生成packeage.json文件
/mnt/d/study/node (master) $ mkdir hello-express
/mnt/d/study/node (master) $ cd hello-express/
/mnt/d/study/node/hello-express (master) $ npm init
- 工程目录安装express,并保存在package.json文件的dependecies list
/mnt/d/study/node/hello-express (master) $ npm install express --save
- 增加index.js文件,内容如下
'use script';
var express = require('express')
var app = express()
var port = 1026
app.get("/", (req, res) => {
res.send("hello world");
})
app.listen(port, ()=>{
console.log("express app running at http://localhost:" + port)
})
- 启动程序
/mnt/d/study/node/hello-express (master) $ node index.js
-
浏览器访问
-
至此,第一个hello程序完成,代码目录结构如下
/mnt/d/study/node (master) $ tree hello-express -L 1
hello-express
├── index.js
├── node_modules
└── package.json
使用express生成标准程序框架
- 安装npx(要求node 8.2.0以上版本)
/mnt/d/study/node (master) $ sudo npm install npx -g
- 使用npx命令生成工程骨架
/mnt/d/study/node (master) $ npx express-generator general-express/
npx: installed 10 in 4.406s
warning: the default view engine will not be jade in future releases
warning: use `--view=jade' or `--help' for additional options
create : general-express/
create : general-express/public/
create : general-express/public/javascripts/
create : general-express/public/images/
create : general-express/public/stylesheets/
create : general-express/public/stylesheets/style.css
create : general-express/routes/
create : general-express/routes/index.js
create : general-express/routes/users.js
create : general-express/views/
create : general-express/views/error.jade
create : general-express/views/index.jade
create : general-express/views/layout.jade
create : general-express/app.js
create : general-express/package.json
create : general-express/bin/
create : general-express/bin/www
change directory:
$ cd general-express/
install dependencies:
$ npm install
run the app:
$ DEBUG=general-express:* npm start
- 生成的骨架目录结构,如下
/mnt/d/study/node (master) $ cd general-express/
/mnt/d/study/node/general-express (master) $ tree . -L 2
.
├── app.js
├── bin
│ └── www
├── package.json
├── public
│ ├── images
│ ├── javascripts
│ └── stylesheets
├── routes
│ ├── index.js
│ └── users.js
└── views
├── error.jade
├── index.jade
└── layout.jade
7 directories, 8 files
- 安装依赖库
/mnt/d/study/node/general-express (master) $ npm install
- 启动程序
/mnt/d/study/node/general-express (master) $ DEBUG=general-express:* npm start
general-express@0.0.0 start /mnt/d/study/node/general-express
node ./bin/www
general-express:server Listening on port 3000 +0ms