iT邦幫忙

3

node.js - express #7

pyk 2017-05-25 15:47:2626203 瀏覽

上周雖然提到了ejs
但我想從 Web Development with Node Express O'Reilly 的這本書重新做express的專案

這本書會逐步完成一個旅行社的網站

第七個應用:開發旅行社網站(1)

  1. 首先先建立一個 project 資料夾,

  2. 並在底下建立 meadowlark 資料夾 (這個名稱是旅行社的名字,取自一種鳥類)

  3. 進入到該資料夾

$ cd <path>/project/meadowlark
  1. 建立管理所有用到套件的文件,這段指令會建立package.json
npm init
  1. 安裝 express到這個專案,會將express相關的程式碼安裝到 node_modules 資料夾
npm install --save express
  1. 在管理時,由於 node_modules 裡存放的程式碼都能用npm重新生成,
    因此不希望存放下來,所以要新增一個文件 .gitignore 避免浪費空間
# ignore packages installed by npm
node_modules
# put any other files you don't want to check in here,
# such as .DS_Store (OSX), *.bak, etc.
  1. 新增 meadowlark.js
var express = require('express');
var app = express();
app.set('port', process.env.PORT || 3000);

//404頁面
app.use(function(req, res){
res.type('text/plain');
res.status(404);
res.send('404 - Not Found');
});

//505頁面
app.use(function(err, req, res, next){
console.error(err.stack);
res.type('text/plain');
res.status(500);
res.send('500 - Server Error');
});

app.listen(app.get('port'), function(){
console.log( 'Express started on http://localhost:' +
app.get('port'));
});

這樣就會建立一個express的server,但因為還沒有設定路由,所以會出現404的畫面

http://ithelp.ithome.com.tw/upload/images/20170525/20105154cqtiswCp7J.png

  1. 設定路由
var express = require('express');
var app = express();

app.set('port',process.env.PORT || 3000);

//Home page
app.get('/',function(req,res){
	res.type('text/plain');
	res.send('Meadowlark Travel');
});

//About Page
app.get('/about',function(req,res){
	res.type('text/plain');
	res.send('About Meadowlark Travel');
})

//製作404畫面
app.use(function(req,res){
	res.type('text/plain');
	res.status(404);
	res.send('404 - Not Found');
});

//505畫面
app.use(function(err,req,res,next){
	console.log(err.stack);
	res.type('text/plain');
	res.status(500);
	res.send('500 - Server Error');
});

app.listen(app.get('port'), function(){
	console.log('Express start on http://localhost:' + app.get('port'));
});

app.get 是用來寫路由的方法

app.verb 在Express當中這裡的verb是用來表示HTTP的動作,例如get/post

app.get 本身會忽略大小寫、反斜線、也不考慮查詢的字串,
因此 /About/ABOUT/about//about?=foo/about/?=foo 都不影響結果

res.type 也是express提供的方式,能夠設定Content Type

在製作404和500畫面時則是用到 app.use 這是一種middleware的處理方式


圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言