随机诗词API实战:Vue项目接入完整示例与5个常见坑
一、写在前面:为什么需要随机诗词API
很多开发者想在个人网站、博客或管理后台的空白区域增加一点文化气息——随机展示一首古诗词,既优雅又能缓解页面空洞感。但真正动手时,却容易陷入几个困境:
- 找不到稳定又免费的诗词接口,试了几个要么挂掉要么返回格式混乱;
- 前端跨域报错,本地开发好好的,部署后却拿不到数据;
- 没有做错误处理,接口一旦超时或限流,页面直接白屏;
- 随机逻辑太简陋,每次刷新重复率高,体验打折。
本文以「今日诗词」这款公开免费的随机诗词API为例(你同样可以在ApiZero等聚合平台上找到同类接口),一步步带你完成从调试、封装到完整Vue组件开发的全流程,并总结5个最容易被忽视的坑。代码全部可运行,复制到项目里稍作修改就能用。
二、API 选择与调试
2.1 接口推荐
我们选用https://v1.jinrishici.com/all.json,这是一个长期维护的免费接口,返回随机诗词(包含诗句、出处、作者)。你也可以在 ApiZero 平台上找到类似的随机诗词API,并在线调试。两个平台都支持 HTTPS,不需要申请key,开箱即用。
2.2 接口返回格式
用浏览器或Postman请求该地址,得到类似以下JSON:
{ "content": "床前明月光,疑是地上霜。", "origin": "静夜思", "author": "李白", "category": "唐诗" }注:若返回空或异常,说明接口暂时不可用,建议换用ApiZero上的备用接口。
2.3 快速验证
打开浏览器DevTools -> Console,直接执行:
fetch('https://v1.jinrishici.com/all.json') .then(res => res.json()) .then(console.log) .catch(console.error)看到json对象就说明通了。
三、Vue 项目集成步骤
3.1 初始化项目 & 安装依赖
# 用Vite创建Vue3项目 npm create vite@latest poetry-app -- --template vue cd poetry-app npm install # 安装请求库 npm install axios3.2 封装请求模块
src/utils/request.js:
import axios from 'axios' const api = axios.create({ baseURL: 'https://v1.jinrishici.com', timeout: 5000 }) // 响应拦截器 api.interceptors.response.use( response => { const data = response.data // 统一处理业务码,这里接口直接返回正文,不需要额外逻辑 return data }, error => { console.error('请求失败:', error.message) return Promise.reject(error) } ) export default api3.3 创建诗词API服务
src/api/poetry.js:
import request from '@/utils/request' export function getRandomPoetry() { return request.get('/all.json') }3.4 编写组件:src/components/PoetryDisplay.vue
<template> <div class="poetry-card"> <div v-if="loading" class="loading">正在为您寻诗...</div> <div v-else-if="error" class="error"> <p>☹️ 诗意暂时迷路了</p> <button @click="fetchPoetry">再试一次</button> </div> <div v-else class="poetry-content"> <p class="content">{{ poetry.content }}</p> <p class="source">—— {{ poetry.author }}《{{ poetry.origin }}》</p> </div> </div> </template> <script setup> import { ref, onMounted } from 'vue' import { getRandomPoetry } from '@/api/poetry' const poetry = ref({ content: '', origin: '', author: '' }) const loading = ref(true) const error = ref(false) const fetchPoetry = async () => { loading.value = true error.value = false try { const res = await getRandomPoetry() poetry.value = { content: res.content || '无题', origin: res.origin || '佚名', author: res.author || '无名氏' } } catch (e) { error.value = true } finally { loading.value = false } } onMounted(fetchPoetry) </script> <style scoped> .poetry-card { padding: 20px; background: #f9f7f1; border-radius: 8px; text-align: center; min-height: 120px; } .content { font-size: 1.2rem; color: #333; line-height: 1.8; } .source { margin-top: 12px; color: #999; font-style: italic; } .error button { padding: 6px 16px; border: 1px solid #ccc; border-radius: 4px; cursor: pointer; } </style>3.5 在页面中使用
src/App.vue:
<template> <div class="app"> <h1>今日·诗意</h1> <PoetryDisplay /> </div> </template> <script setup> import PoetryDisplay from './components/PoetryDisplay.vue' </script>四、5个常见坑与排查方法
下表整理了集成随机诗词API时最容易被忽视的问题,每个都配有解决方案。
| 坑点 | 典型现象 | 原因 | 解决方案 |
|---|---|---|---|
| 跨域报错 | Access-Control-Allow-Origin缺失 | 浏览器同源策略 | 开发环境用Vite proxy;生产环境后端转发或要求服务商开CORS |
| 接口限流 | 突然返回空或503 | API有每分钟/小时请求限制 | 前端加本地缓存(localStorage),相同诗词不再重复请求;或使用防抖 |
| 字段名变化 | 渲染为“undefined” | 接口升级或备用接口字段不同 | 映射时设置默认值(如 `res.content |
| 网络延迟 | 页面长时间空白 | 无加载状态 | 使用loading变量控制骨架屏或转圈 |
| 同首循环 | 两次刷新显示相同诗词 | 接口伪随机,短时间内重复 | 客户端维护已显示列表,结合数组去重后展示 |
4.1 跨域终极方案(Vite Proxy)
修改vite.config.js:
export default defineConfig({ server: { proxy: { '/jinrishici': { target: 'https://v1.jinrishici.com', changeOrigin: true, rewrite: path => path.replace(/^\/jinrishici/, '') } } } })然后请求改为/jinrishici/all.json。
4.2 本地缓存避免重复请求
const cache = JSON.parse(localStorage.getItem('poetryCache') || '[]') // 获取新诗词时检查是否已经拉取过 const fetchUniquePoetry = async () => { let data do { data = await getRandomPoetry() } while (cache.some(item => item.content === data.content)) cache.push(data) localStorage.setItem('poetryCache', JSON.stringify(cache.slice(-50))) // 保留最近50首 return data }五、最佳实践:让诗词展示更优雅
- 动画过渡:使用
<Transition>包裹内容,切换时有淡入效果。 - 随机刷新按钮:加一个刷新图标,触发
fetchPoetry,同时闪烁一下。 - 多数据源fallback:如果主接口挂了,轮询备用接口(例如ApiZero上的同类API)。
- 服务器端缓存(SSR):如果使用Nuxt,可以在服务端预取一首诗词作为初始状态,减少前端白屏时间。
<button @click="rotatePoetry" title="换一首"> 🎲 随机 </button> <script setup> const rotatePoetry = async () => { await fetchPoetry() // 触发CSS动画 animation.value = true setTimeout(() => animation.value = false, 500) } </script>六、总结
本文从真实开发痛点出发,带你走完了“选接口 → 调试 → 封装 → 组件化 → 避坑”的完整链路。核心公式是:稳定API + 合理的请求模块 + 完备的loading/error状态 + 兜底策略。
如果你现在手头正有一个Vue项目,不妨复制上面的PoetryDisplay.vue直接运行。遇到问题不要慌,对照表格逐一排查。如果你在项目中遇到了类似接口调用报错(比如其他古诗API、一言API等),欢迎把错误信息贴在评论区,我会按场景补充排查思路。
收藏本文,下次给网站加“诗意侧边栏”时就能直接用了。觉得有用的话,点个赞再走呗 😄