六角體驗營 # Todolist RESTful API : 開發新刪修查的API (實作1) - 環境設置(postman) > 複習筆記 : [node.js - Node.js 核心模組 : createServer](https://hackmd.io/udzaGxIhThqXOPoTOu15_Q?view) <br> ## 1. 建立環境 * #### STEP 1-1. 產生package.json ```termainal npm init ``` * #### STEP 1-2. 建立伺服器 createServer > 筆記 : request 發出請求 / response 回應 > 可透過console.log(request)了解使用者資訊 * 專案中新增 server.js 檔案 * terminal 執行 node server.js 或 nodemon server.js * 開啟 server (如下) ```js= const http = require('http'); //載入http模組 //監聽函式 const requestListener = (request,response)=>{ //console.log(request); //可透過請求獲得使用者(發出請求)資訊 //console.log(request.url); //console.log(request.method); response.writeHead(200,{"Content-Type":"text/plain"}); //回應格式 response.write("hello"); //回應文字 response.end(); //結束回應 } const server = http.createServer(requestListener); server.listen(3005); //給port號 ``` * #### STEP 1-3. 執行node server.js 開啟網址 * 執行結束後可在網址以localcast:port號檢視,應會呈現回應的hello文字 ``` 127.0.0.1:3005 localhost:3005 ``` ![](https://hackmd.io/_uploads/Bka-YZTbT.png) <br> ## 2. postman 發出請求(get / post) * #### STEP 2-1. 觀察request資訊 request 是一個物件資料,內含使用者資訊 ```js= const requestListener = (request,response)=>{ //request 是一個物件資料,內含使用者資訊 console.log(request); //觀察url及method資訊 console.log(request.url); console.log(request.method); ... }; ``` * #### STEP 2-2. 發送請求 * terminal執行node server.js / nodemon server.js * postman 修改url網址、請求方法(下圖) ![](https://hackmd.io/_uploads/Bk_m6b6-T.png) * #### STEP 2-3. termainal回應資料 ``` /hiii~ POST ``` <br> ## 3. 新增首頁測試網址與 404 頁面 * #### STEP 3-1. 發送請求 ```js= const http = require('htpp'); const requestener = (request,response)=>{ const headers = {"Content-Type":"text/plain"}; //1. 當首頁的情況且網頁重整時(get方法使用) if(request.url == '/' && request.method == "GET"){ response.writeHead(200,headers); response.write('index'); response.end(); //2. 使用其他方法的情況(ex.DELETE) // 需要透過postman觀察 }else if(request.url == '/' && request.method == "DELETE"){ response.writeHead(200,headers); response.write('Delete'); response.end(); //3. 找不到首頁時 }else{ response.writeHead(404,headers); response.write("not found 404"); response.end(); } } const server = http.createServer(requestListener); server.listen(3005); ``` ## 4. 調整表頭資訊,設置回傳 JSON 與 cors 資訊(跨網域) * #### STEP 4-1. 表頭資訊 * Access-Control-Allow-Headers : 允許的客戶端(瀏覽器)請求中可以包含的 HTTP 請求表頭 * 'Content-Type'(內容類型) * 'Authorization'(授權) * 'Content-Length'(內容長度) * 'X-Requested-With': 自定義的,用於指示請求是由 XMLHTTPRequest(XHR)對象發起的 * Access-Control-Allow-Origin : 其他伺服器IP均能造訪網站 * Access-Control-Allow-Methods : 跨網域可以使用的方法 * Content-Type : 回傳數據改為json格式資料 ```= const headers = { 'Access-Control-Allow-Headers': 'Content-Type, Authorization, Content-Length, X-Requested-With', 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Methods': 'PATCH, POST, GET,OPTIONS,DELETE', 'Content-Type': 'application/json' } ``` * #### STEP 4-2. postman中測試headers是否成功引用 若有包含允許的headers資訊,代表成功 ![](https://hackmd.io/_uploads/BJdAgQab6.png =80%x) * #### STEP 4-3. 設定response回應的資料內容(轉換成JSON字串) 網路請求只能以字串傳送 -> 使用 **JSON.stringify()** ```js= //修改response.write內容 if(request.url=='/' && request.method == "GET"){ response.writeHead(200,headers); response.write(JSON.stringify({ "status":"success", data:[], //回傳空陣列 })); response.end(); //else if 可拿掉,僅為測試方法用 }else{ response.writeHead(200,headers); response.write(JSON.stringify({ "status":"false", "message":"無此網站路由" })); response.end(); } ``` * #### STEP 4-4. 透過postman / 127.0.0.1:3005 測試 * 成功到達首頁 ![](https://hackmd.io/_uploads/ByWbSmpWa.png =70%x) * 不存在的網址 ![](https://hackmd.io/_uploads/BkWmHm6-T.png =70%x) <br> ## 5. preflight options API 預先檢查機制 > [MDN:跨來源資源共用(CORS)](https://developer.mozilla.org/zh-TW/docs/Web/HTTP/CORS) * 可在DevTools network中觀察到跨域(cors)的瀏覽器請求,會被發送兩次(type: preflight / fetch) ![](https://hackmd.io/_uploads/SyiSimTb6.png) * 原因是因跨網域(domain)的請求會較嚴謹 * ex.localhost向某API("https://.....")發送請求 * 第一次先發出網址請求 options * 第二次才對 API 使用 method 發出請求 ![](https://hackmd.io/_uploads/H1Q95ma-a.png) <br> ## 6. 設定 options API * #### STEP 6-1. 加入OPTIONS的情況 -> 直接結束 ```js= //修改response.write內容 if(request.url=='/' && request.method == "GET"){ response.writeHead(200,headers); response.write(JSON.stringify({ "status":"success", data:[], //回傳空陣列 })); response.end(); //options方法的情況 }else if(request.method == "OPTIONS"){ response.writeHead(200,headers); //數據傳遞OK response.end(); //送回去給伺服器 }else{ response.writeHead(200,headers); response.write(JSON.stringify({ "status":"false", "message":"無此網站路由" })); response.end(); } ``` * #### STEP 6-2. postman 使用 options 方法測試 不會得到回呼,因為response.end(); ![](https://hackmd.io/_uploads/SJfFlP6bp.png =80%x) <br> > 接續 : > [**Todolist RESTful API : 開發新刪修查的API (實作2) - CRUD ( GET / POST API )**](https://hackmd.io/fjk5zVcFRwaVnQND2iUNfQ?view)