理解異步編程:Promise與async/await的應用

學習Node.js:如何使用JavaScript進行後端開發




1. 介紹 Node.js

Node.js 是什麼?

Node.js 是一個基於 Chrome V8 引擎的 JavaScript 運行環境,它允許開發者在伺服器端運行 JavaScript 代碼。與傳統的 JavaScript 只用於前端不同,Node.js 使得開發者可以使用 JavaScript 進行全端開發(Full Stack Development)。

為何選擇 Node.js 進行後端開發?

Node.js 具備以下優勢,使其成為後端開發的熱門選擇:

  1. 統一的技術棧:前後端均可使用 JavaScript,提高開發效率。

  2. 非阻塞 I/O:使用事件驅動與異步處理,使應用具備高併發能力。

  3. 輕量且高效:適用於即時應用,如聊天應用、流媒體服務等。

  4. 強大的生態系統:擁有龐大的 npm(Node Package Manager)生態,可快速集成第三方模組。

Node.js 的應用場景

  • Web 應用後端:如 RESTful API、GraphQL API 服務

  • 即時應用:聊天室、即時通知、線上遊戲

  • 微服務架構:構建可擴展、靈活的服務

  • 物聯網(IoT):處理設備數據流

2. 設置 Node.js 開發環境

安裝 Node.js 與 npm

可從 Node.js 官網 下載安裝程式,並使用以下指令確認安裝成功:

node -v
npm -v

建立第一個 Node.js 專案

使用以下指令建立專案目錄並初始化 package.json

mkdir my-node-app && cd my-node-app
npm init -y

安裝 Express 框架

Express 是最流行的 Node.js Web 框架,安裝方式如下:

npm install express

3. 建立簡單的 Node.js 伺服器

Node.js 提供內建的 http 模組,可用於建立伺服器:

const http = require('http');

const server = http.createServer((req, res) => {
    res.writeHead(200, { 'Content-Type': 'text/plain' });
    res.end('Hello, Node.js!');
});

server.listen(3000, () => {
    console.log('Server running at http://localhost:3000');
});

也可以使用 Express 來簡化伺服器開發:

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

app.get('/', (req, res) => {
    res.send('Hello, Express!');
});

app.listen(3000, () => {
    console.log('Server is running on port 3000');
});

4. 處理 HTTP 請求與 RESTful API 設計

什麼是 RESTful API?

REST(Representational State Transfer)是一種 API 設計架構,主要透過 HTTP 方法(GET、POST、PUT、DELETE)與資源進行交互。

Express 中的路由處理

app.get('/users', (req, res) => {
    res.json([{ id: 1, name: 'Alice' }, { id: 2, name: 'Bob' }]);
});

app.post('/users', (req, res) => {
    res.send('新增使用者');
});

5. 與資料庫交互

選擇合適的資料庫(SQL vs NoSQL)

  • SQL(MySQL、PostgreSQL):適用於結構化數據

  • NoSQL(MongoDB):適用於靈活數據存儲

連接 MongoDB

安裝 mongoose:

npm install mongoose

建立 MongoDB 連接並進行 CRUD 操作:

const mongoose = require('mongoose');

mongoose.connect('mongodb://localhost:27017/mydb', { useNewUrlParser: true, useUnifiedTopology: true });

const UserSchema = new mongoose.Schema({ name: String, age: Number });
const User = mongoose.model('User', UserSchema);

User.create({ name: 'Alice', age: 25 }).then(user => console.log(user));

6. 進階 Node.js 開發概念

非阻塞 I/O 與事件驅動架構

Node.js 使用異步 I/O 操作,確保高效能處理大量請求。

const fs = require('fs');

fs.readFile('test.txt', 'utf8', (err, data) => {
    if (err) throw err;
    console.log(data);
});

使用 WebSocket 進行即時通訊

安裝 ws 套件並建立 WebSocket 伺服器:

npm install ws
const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8080 });

wss.on('connection', ws => {
    ws.send('Welcome to WebSocket Server');
    ws.on('message', message => console.log(`Received: ${message}`));
});

7. API 安全性與最佳實踐

驗證與授權(JWT)

安裝 JWT 模組:

npm install jsonwebtoken
const jwt = require('jsonwebtoken');
const token = jwt.sign({ userId: 1 }, 'secretkey', { expiresIn: '1h' });
console.log(token);

保護 API 免受攻擊

  • CORS 啟用

    const cors = require('cors');
    app.use(cors());
    
  • 輸入驗證:使用 express-validator 避免 SQL 注入

8. 部署與伺服器管理

使用 PM2 進行進程管理

npm install pm2 -g
pm2 start app.js

部署到雲端(Heroku)

git init
heroku create my-node-app
git push heroku main

9. 實戰:構建一個簡單的 API 服務

建立使用者 API 服務:

app.use(express.json());

app.post('/users', (req, res) => {
    const { name, age } = req.body;
    res.json({ id: Date.now(), name, age });
});

整合 React 前端請求 API:

fetch('http://localhost:3000/users', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ name: 'Alice', age: 25 })
}).then(res => res.json()).then(data => console.log(data));

10. 總結與進一步學習

透過本教程,我們學會了:
✅ 設置 Node.js 環境
✅ 建立 RESTful API
✅ 連接資料庫
✅ 部署至雲端

下一步可學習:

  • GraphQL API

  • 微服務架構

  • 使用 Docker 進行容器化部署

希望這篇文章能幫助你開啟 Node.js 的開發之旅! 🚀

留言