2024-08-09|閱讀時間 ‧ 約 29 分鐘

使用 Node.js 建立簡易伺服器並解決 CORS 問題

在這篇教學文章中,我們將展示如何使用 Node.js 建立一個簡單的伺服器,並解決常見的跨來源資源共享(CORS)問題,確保伺服器能夠接收並處理來自不同來源的資料。


什麼是 CORS?

CORS(Cross-Origin Resource Sharing)是一種安全機制,當瀏覽器發送 AJAX 請求到不同來源的伺服器時,瀏覽器會檢查伺服器是否允許這種跨來源的請求。如果伺服器沒有正確設置 CORS,請求將被瀏覽器阻止,導致伺服器無法收到資料。

1. 初始化專案並安裝必要套件

首先,我們需要初始化一個新的 Node.js 專案,並安裝 expresscors 套件。

  1. 打開終端機,執行以下命令來初始化專案:
    npm init -y
    這會建立一個 package.json 檔案,並設定一些預設的專案設定。
  2. 安裝 expresscors 套件:
    npm install express cors
    express 是一個輕量的 Node.js web 應用程式框架,而 cors 套件可以幫助我們輕鬆地處理 CORS 問題。

2. 建立伺服器端程式碼並啟用 CORS

接下來,我們會建立一個名為 server.js 的檔案,並添加伺服器端程式碼。這個程式會建立一個簡單的伺服器,並處理 CORS。

  1. 建立 server.js 檔案,並添加以下內容:
    const express = require('express');
    const cors = require('cors'); // 引入 cors 套件
    const app = express();
    const port = 3000;

    app.use(express.json());
    app.use(cors()); // 啟用 CORS

    // 簡單的 GET 路由
    app.get('/', (req, res) => {
    res.send('Hello, World!');
    });

    // POST 路由來接收資料
    app.post('/data', (req, res) => {
    const receivedData = req.body;
    console.log('Received data:', receivedData);
    res.send('Data received');
    });

    app.listen(port, () => {
    console.log(`Server is running on http://localhost:${port}`);
    });
    在這段程式碼中,我們引入了 cors 套件,並通過 app.use(cors()) 啟用了 CORS 支援,這樣伺服器便允許任何來源發送請求。

3. 建立使用者端 HTML 檔案

接下來,我們會建立一個簡單的 HTML 檔案,包含一個表單來發送資料到伺服器。

  1. 建立 client.html 檔案,並添加以下內容:
    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Client</title>
    </head>
    <body>
    <h1>Send Data to Server</h1>
    <form id="dataForm">
    <label for="data">Data:</label>
    <input type="text" id="data" name="data" required>
    <button type="submit">Send</button>
    </form>

    <script>
    document.getElementById('dataForm').addEventListener('submit', function(event) {
    event.preventDefault();
    const data = { data: document.getElementById('data').value };

    fetch('http://localhost:3000/data', {
    method: 'POST',
    headers: {
    'Content-Type': 'application/json',
    },
    body: JSON.stringify(data),
    })
    .then(response => response.text())
    .then(responseText => {
    alert('Response from server: ' + responseText);
    })
    .catch(error => {
    console.error('Error:', error);
    });
    });
    </script>
    </body>
    </html>
    在這個 HTML 檔案中,我們建立了一個包含輸入框和提交按鈕的表單。使用 JavaScript 來攔截表單的提交,並使用 fetch 函式將資料發送到伺服器。

4. 啟動伺服器

現在,我們可以啟動伺服器。在終端機中運行以下命令:

node server.js

您應該會看到以下訊息,表示伺服器已成功啟動:

Server is running on http://localhost:3000

5. 測試發送資料

打開瀏覽器,開啟 client.html 檔案。填寫表單並提交,這次應該不會再遇到 CORS 問題,伺服器將能夠成功接收資料,並在終端機中打印收到的資料。

總結

通過這篇教學,我們學習了如何使用 Node.js 建立簡易伺服器,並解決 CORS 問題。當我們希望伺服器接收來自不同來源的請求時,處理 CORS 是必不可少的步驟。希望這篇文章能幫助您順利解決在開發過程中遇到的 CORS 問題。如果有任何問題,歡迎隨時提出。

分享至
成為作者繼續創作的動力吧!
© 2024 vocus All rights reserved.