測試 API 結果時常常需要 fake data 做實際測試,架設 http server 有點小題大作,我們可以利用 express.js 迅速搭建測試用的 API server。
首先安裝相關套件:
npm i --save express cors
接著建立一支 server.js,程式如下:
const express = require('express'); const app = express(); const port = 8080; const fs = require("fs"); const path = require("path"); const cors = require("cors"); app.use(cors()); function getFile(fileName) { return JSON.parse(fs.readFileSync(path.join(__dirname, "data", `${fileName}.json`))); } app.get('/api', (req, res) => { res.json(getFile('index')); }); app.listen(port, () => { console.log(`Example app listening on port ${port}`); })
index.json 內容如下:
{ "status": true, "data": "hello world" }
有時候 json 的內容很龐大,我們不希望負責 route 的檔案長度過長不好維護,所以我這邊 parse 了 data 目錄裡指定的 .json 檔案返回,接著只要執行 node server.js
後就可以在 http://localhost:8080/api
看到正確的內容了。