建立 API 路由

API 路由 (API Routes) 讓您可以在 Next.js 應用程式中建立 API 端點。您只需在 pages/api 目錄中建立一個符合以下格式的函式 (function) 即可:

// req = HTTP 傳入訊息, res = HTTP 伺服器回應
export default function handler(req, res) {
  // ...
}

關於上述請求處理器的更多資訊,請參閱 API 路由文件

這些路由可以部署為無伺服器函式 (Serverless Functions,也稱為 Lambda)。

建立簡單的 API 端點

讓我們實際嘗試。在 pages/api 目錄中建立一個名為 hello.js 的檔案,並輸入以下程式碼:

export default function handler(req, res) {
  res.status(200).json({ text: 'Hello' });
}

嘗試在 http://localhost:3000/api/hello 存取它。您應該會看到 {"text":"Hello"}。請注意:

就是這麼簡單!在結束本課程之前,讓我們在下一頁討論一些使用 API 路由 (API Routes) 的技巧。

On this page