Express(0) - Hello world

Express是一個簡便且靈活的 JS web 應用開發框架。


1. 建立專案:

開啟一個資料夾並安裝 Express 套件。

$ mkdir ExpressApp
$ cd ExpressApp
$ npm init
$ npm install express --save

2. 設定 app:

新增一個 index.js 作為程式的進入點。

$ touch index.js

編輯 index.js,設定 / 的 response 及服務使用的 port:

const express = require("express");
const app = express();

// router
app.get("/", (req, res) => res.send("Hello world"));

// set the port
app.listen(4000, () => console.log("Listening on port 4000"));

JS 習慣使用 Arrow function 傳入一個函式,。

(參數) => { 函式體 }

單行時函式體的大括號可以省略。


3. 啟動 app:

啟動 app,在瀏覽器輸入 http://127.0.0.1:4000 就可以看到 "Hello world"。

$ node index.js

留言

熱門文章