文章详情

返回首页

CF上的Workers搭建汇率计算器

分享文章 作者: Ws01 创建时间: 2025-11-24 📝 字数: 10,043 字 👁️ 阅读: 13 次

addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request))
})

async function handleRequest(request) {
const url = new URL(request.url)

// 处理 GET 请求,返回 HTML 页面
if (request.method === 'GET' && url.pathname === '/') {
return new Response(htmlContent, {
headers: { 'Content-Type': 'text/html' }
})
}

// 处理汇率查询请求
if (request.method === 'GET' && url.pathname === '/exchange-rate') {
const fsym = url.searchParams.get('fsym')
const tsym = url.searchParams.get('tsym') || 'CNY'

try {
let rate
const resp = await fetch(https://api.exchangerate-api.com/v4/latest/${fsym})
const data = await resp.json()

if (data.rates[tsym]) {
rate = data.rates[tsym]
} else {
const resp2 = await fetch(https://womjj.deno.dev/rate?fsym=${fsym}&tsym=${tsym})
const obj = await resp2.json()
rate = obj[tsym] || obj['CNY']
}

return new Response(JSON.stringify({ rate }), {
headers: { 'Content-Type': 'application/json' }
})
} catch (error) {
return new Response(JSON.stringify({ error: '获取汇率失败' }), {
status: 500,
headers: { 'Content-Type': 'application/json' }
})
}
}

return new Response('Not Found', { status: 404 })
}

// 嵌入 HTML 页面内容
const htmlContent = `

📅汇率转换器

📅汇率转换

结果将在这里显示