版權聲明:本文為部落客chszs的原創文章,未經部落客允許不得轉載。 https://blog.csdn.net/chszs/article/details/8869655
ExpressJS入門指南
作者:chszs,轉載需注明。部落格首頁:
http://blog.csdn.net/chszs一、我們建立項目目錄。
> md hello-world
二、進入此目錄,定義項目配置檔案package.json。
為了準确定義,可以使用指令:
D:\tmp\node\hello-world> npm info express version
npm http GET https://registry.npmjs.org/express
npm http 200 https://registry.npmjs.org/express
3.2.1
現在知道ExpressJS架構的最新版本為3.2.1,那麼配置檔案為:
{
"name": "hello-world",
"description": "hello world test app",
"version": "0.0.1",
"private": true,
"dependencies": {
"express": "3.2.1"
}
}
三、使用npm安裝項目依賴的包。
> npm install
一旦npm安裝依賴包完成,項目根目錄下會出現node_modules的子目錄。項目配置所需的express包都存放于這裡。如果相驗證,可以執行指令:
> npm ls
PS D:\tmp\node\hello-world> npm ls
npm WARN package.json [email protected] No README.md file found!
[email protected] D:\tmp\node\hello-world
└─┬ [email protected]
├── [email protected]
├── [email protected]
├─┬ [email protected]
│ ├── [email protected]
│ ├── [email protected]
│ └── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
└─┬ [email protected]
└── [email protected]
此指令顯示了express包及其依賴關系。
四、建立應用程式
現在開始建立應用程式自身。建立一個名為app.js或server.js的檔案,看你喜歡,任選一個。引用express,并使用express()建立一個新應用:
// app.js
var express = require('express');
var app = express();
接着,我們可以使用app.動詞()定義路由。
比如使用"GET /"響應"Hello World"字元串,因為res、req都是Node提供的準确的對象,是以你可以調用res.pipe()或req.on('data', callback)或者其它。
app.get('/hello.txt', function(req, res){
var body = 'Hello World';
res.setHeader('Content-Type', 'text/plain');
res.setHeader('Content-Length', body.length);
res.end(body);
});
ExpressJS架構提供了更高層的方法,比如res.send(),它可以省去諸如添加Content-Length之類的事情。如下:
app.get('/hello.txt', function(req, res){
res.send('Hello World');
});
現在可以綁定和監聽端口了,調用app.listen()方法,接收同樣的參數,比如:
app.listen(3000);
console.log('Listening on port 3000');
五、運作程式
現在運作程式,執行指令:
> node app.js
用浏覽器通路位址:http://localhost:3000/hello.txt
可以看到輸出結果:
Hello World