教學/用 React 建立貨幣換算器

用 React 建立貨幣換算器

用 React 建立貨幣換算器. 包含程式碼、快取及數據新鮮度的實用指南。

ERexchangerate.dev·Sep 20, 2026·閱讀約 7 分鐘

在伺服器實作,不公開憑證,並保留數據來源及觀測時間。

重點
只在伺服器保存 API 金鑰。
驗證貨幣代碼及金額。
快取成功回應。
顯示來源及觀測時間。

步驟 1

請在伺服器執行、驗證輸入,並保留回應元數據。

程式碼範例copy
import { NextRequest, NextResponse } from "next/server";

export async function GET(request: NextRequest) {
  const { searchParams } = request.nextUrl;
  const from = searchParams.get("from")?.toUpperCase();
  const to = searchParams.get("to")?.toUpperCase();
  const amount = Number(searchParams.get("amount"));
  if (!from || !to || !Number.isFinite(amount) || amount < 0) {
    return NextResponse.json({ error: "invalid_input" }, { status: 400 });
  }

  const response = await fetch(
    `https://api.exchangerate.dev/v1/convert/${from}/${to}/${amount}`,
    {
      headers: { Authorization: `Bearer ${process.env.EXCHANGERATE_API_KEY}` },
      signal: AbortSignal.timeout(5000),
      next: { revalidate: 60 },
    },
  );
  return NextResponse.json(await response.json(), { status: response.status });
}

步驟 2

程式碼範例copy
"use client";

import { FormEvent, useState } from "react";

type ConversionResult = {
  converted: string;
  source: string;
  data_updated_at: string;
};

export function CurrencyConverter() {
  const [amount, setAmount] = useState("100");
  const [result, setResult] = useState<ConversionResult | null>(null);
  const [error, setError] = useState("");
  const [loading, setLoading] = useState(false);

  async function submit(event: FormEvent) {
    event.preventDefault();
    setLoading(true); setError("");
    try {
      const params = new URLSearchParams({ from: "USD", to: "EUR", amount });
      const response = await fetch(`/api/convert?${params}`);
      const body = await response.json();
      if (!response.ok) throw new Error(body.error ?? "conversion_failed");
      setResult(body);
    } catch (caught) {
      setError(caught instanceof Error ? caught.message : "conversion_failed");
    } finally { setLoading(false); }
  }

  return <form onSubmit={submit}>
    <input value={amount} onChange={(event) => setAmount(event.target.value)} inputMode="decimal" />
    <button disabled={loading}>{loading ? "Converting…" : "Convert"}</button>
    {error && <p role="alert">{error}</p>}
    {result && <output>{result.converted} EUR · {result.source} · {result.data_updated_at}</output>}
  </form>;
}

步驟 3

  • 只在伺服器保存 API 金鑰。
  • 驗證貨幣代碼及金額。
  • 快取成功回應。
  • 顯示來源及觀測時間。
指南
這些匯率只供參考,並非結算價格。
ER
exchangerate.dev
為開發者而設的實用貨幣數據指南。

延伸閱讀

指南開發者貨幣換算 API閱讀 指南用 JavaScript 同 Node.js 做貨幣換算閱讀 指南API errors and response fields閱讀