完整程式碼,請洽: https://github.com/Zrn-code/Node-js-tutorial/tree/node-04
# 請求方的重要物件
server.js | const http = require('http'); |
| |
| const server = http.createServer((req , res) => { |
| console.log(req.url,req.method); |
| }); |
| server.listen(3000,'localhost', () => { |
| console.log(`listening for requests on post 3000`); |
| }); |
終端機 | PS C:\Users\user\Documents\tuts\node>node server.js |
| listening for requests on post 3000 |
| // 當用戶造訪 localhost:3000 |
| / GET |
| // 當用戶造訪 localhost:3000/about |
| /about GET |
# 回應方的重要物件
# 回應文字
| const http = require('http'); |
| const server = http.createServer((req , res) => { |
| res.setHeader('Content-Type','text/plain'); |
| res.write('Hello, Zrn!!'); |
| res.end(); |
| }); |
| server.listen(3000,'localhost', () => { |
| console.log(`listening for requests on post 3000`); |
| }); |
# 回應 html
| const http = require('http'); |
| const server = http.createServer((req , res) => { |
| res.setHeader('Content-Type','text/html'); |
| res.write('<p>hello, Zrn!!</p>'); |
| res.write('<p>hello, Zrn again!!</p>'); |
| res.end(); |
| }); |
| server.listen(3000,'localhost', () => { |
| console.log(`listening for requests on post 3000`); |
| }); |
# 回傳 html 檔案
使用之前學過的 fs
模組的讀取函式,就可以將回應的內容寫成一個檔案,一併的回應出來
| const http = require('http'); |
| const fs = require('fs'); |
| const server = http.createServer((req , res) => { |
| res.setHeader('Content-Type','text/html'); |
| |
| fs.readFile('./views/index.html',(err, data)=>{ |
| if(err){ |
| console.log(err); |
| res.end(); |
| } else { |
| res.end(data); |
| } |
| }); |
| }); |
| server.listen(3000,'localhost', () => { |
| console.log(`listening for requests on post 3000`); |
| }); |
# 導入路徑
使用 switch
判斷當前請求方的網址,回應出不同的 html 頁面
| const server = http.createServer((req , res) => { |
| res.setHeader('Content-Type','text/html'); |
| |
| let path = './views'; |
| switch(req.url){ |
| case '/': |
| path += 'index.html'; |
| break; |
| case '/about': |
| path += 'about.html'; |
| break; |
| default: |
| path += '404.html'; |
| break; |
| } |
| fs.readFile(path,(err, data)=>{ |
| if(err){ |
| console.log(err); |
| res.end(); |
| } else { |
| res.end(data); |
| } |
| }); |
| }); |
# 狀態碼
- 資訊相關的回應 -> 100 ~ 199
- 成功的回應 -> 200 ~ 299
- 重新導向 -> 300 ~ 399
- 用戶端錯誤 -> 400 ~ 499
- 伺服器端錯誤 -> 500 ~ 599
| let path = './views'; |
| switch(req.url){ |
| case '/': |
| path += 'index.html'; |
| res.statusCode = 200; |
| break; |
| case '/about': |
| path += 'about.html'; |
| res.statusCode = 200; |
| break; |
| default: |
| path += '404.html'; |
| res.statusCode = 404; |
| break; |
| } |
# 重新導向
| let path = './views'; |
| switch(req.url){ |
| case '/': |
| path += 'index.html'; |
| res.statusCode = 200; |
| break; |
| case '/about': |
| path += 'about.html'; |
| res.statusCode = 200; |
| break; |
| case '/about-me': |
| res.statusCode = 301; |
| res.setHeader('Location','/about'); |
| res.end(); |
| break; |
| default: |
| path += '404.html'; |
| res.statusCode = 404; |
| break; |
| } |