最近要用Node JS 建立一個後台服務,同事介紹用Express來做。
安裝的過程請參考第2篇"安裝Express" 教學
當你要建立一個專案時,可以透過express-generator
來幫你產生專案所需要的基本內容。
(1)先安裝express-generator
npm install express-generator -g
boywhys-MacBook-Pro:express boywhychen$ sudo npm install express-generator -g Password: /usr/local/bin/express -> /usr/local/lib/node_modules/express-generator/bin/express express-generator@4.13.1 /usr/local/lib/node_modules/express-generator ├── sorted-object@1.0.0 ├── commander@2.7.1 (graceful-readlink@1.0.1) └── mkdirp@0.5.1 (minimist@0.0.8) boywhys-MacBook-Pro:express boywhychen$
(2)建立你的專案,假如名稱叫mysite
express mysite
boywhys-MacBook-Pro:express boywhychen$ express mysite create : mysite create : mysite/package.json create : mysite/app.js create : mysite/public create : mysite/public/javascripts create : mysite/public/images create : mysite/public/stylesheets create : mysite/public/stylesheets/style.css create : mysite/routes create : mysite/routes/index.js create : mysite/routes/users.js create : mysite/views create : mysite/views/index.jade create : mysite/views/layout.jade create : mysite/views/error.jade create : mysite/bin create : mysite/bin/www install dependencies: $ cd mysite && npm install run the app: $ DEBUG=mysite:* npm start boywhys-MacBook-Pro:express boywhychen$
(3) 進入專案資料夾
cd mysite
(4) 安裝專案npm install
boywhys-MacBook-Pro:mysite boywhychen$ npm install npm WARN deprecated jade@1.11.0: Jade has been renamed to pug, please install the latest version of pug instead of jade debug@2.2.0 node_modules/debug └── ms@0.7.1 serve-favicon@2.3.0 node_modules/serve-favicon ├── fresh@0.3.0 ├── parseurl@1.3.1 ├── etag@1.7.0 └── ms@0.7.1 cookie-parser@1.3.5 node_modules/cookie-parser ├── cookie@0.1.3 └── cookie-signature@1.0.6 morgan@1.6.1 node_modules/morgan ├── on-headers@1.0.1 ├── basic-auth@1.0.3 ├── depd@1.0.1 └── on-finished@2.3.0 (ee-first@1.1.1) body-parser@1.13.3 node_modules/body-parser ├── bytes@2.1.0 ├── content-type@1.0.1 ├── depd@1.0.1 ├── qs@4.0.0 ├── on-finished@2.3.0 (ee-first@1.1.1) ├── http-errors@1.3.1 (statuses@1.2.1, inherits@2.0.1) ├── iconv-lite@0.4.11 ├── raw-body@2.1.6 (unpipe@1.0.0, bytes@2.3.0, iconv-lite@0.4.13) └── type-is@1.6.12 (media-typer@0.3.0, mime-types@2.1.11) express@4.13.4 node_modules/express ├── escape-html@1.0.3 ├── array-flatten@1.1.1 ├── cookie-signature@1.0.6 ├── merge-descriptors@1.0.1 ├── content-type@1.0.1 ├── methods@1.1.2 ├── etag@1.7.0 ├── vary@1.0.1 ├── parseurl@1.3.1 ├── cookie@0.1.5 ├── content-disposition@0.5.1 ├── path-to-regexp@0.1.7
(5)啟動專案(這裡是MAC,Windows 啟動字串不太一樣)
DEBUG=mysite:* npm start
oywhys-MacBook-Pro:mysite boywhychen$ DEBUG=mysite:* npm start > mysite@0.0.0 start /Users/boywhychen/express/mysite > node ./bin/www mysite:server Listening on port 3000 +0ms
此時服務己經work起來了, 在瀏覽器打上 http://localhost:3000/
會看到如下圖的畫面代表成功了
參考資料:
Express 中文官網
http://expressjs.com/zh-tw/
安裝Express
http://expressjs.com/zh-tw/starter/installing.html
What is Express? Why use Express?
沒有留言:
張貼留言