建立 Web 應用程式時,顯示連結內容的預覽通常很有用,就像社交媒體平台在共享 URL 時如何顯示連結預覽一樣。因此,除了 url 文字之外,您還可以在 url 旁邊顯示圖片和描述等資訊。
在這篇文章中,我將引導您在 React 應用程式中嵌入鏈接,同時使用 axios 和 Cheerio 獲取 Open Graph 元資料(例如標題、圖像和描述)以抓取目標頁面的 HTML。
我們將建立一個簡單的 EmbeddedLink 元件,用於取得並顯示任何提供的 URL 的 Open Graph 元資料。
在開始之前,請確保您已安裝以下軟體:
您可以使用以下指令安裝 Axios 和 Cheerio:
npm install axios cheerio
我們將建立一個新的 EmbeddedLink 元件,該元件接受 url 為 prop,並從該連結獲取 Open Graph 元數據,稍後我們將使用該元數據。完整程式碼如下:
import React, { useState, useEffect } from 'react'; import axios from 'axios'; import cheerio from 'cheerio'; const EmbeddedLink = ({ url }) => { const [loading, setLoading] = useState(true); const [error, setError] = useState(null); const [imageUrl, setImageUrl] = useState(''); const [title, setTitle] = useState(''); const [description, setDescription] = useState(''); useEffect(() => { const fetchOGData = async () => { try { const response = await axios.get(url, { headers: { 'origin': 'https://mysite.com' } }); const html = response.data; // Parse HTML content using Cheerio const $ = cheerio.load(html); const ogImage = $('meta[property="og:image"]').attr('content'); const ogTitle = $('meta[property="og:title"]').attr('content'); const ogDesc = $('meta[property="og:description"]').attr('content'); setImageUrl(ogImage || ''); setTitle(ogTitle || ''); setDescription(ogDesc || ''); setLoading(false); } catch (error) { setError(error); setLoading(false); } }; fetchOGData(); }, [url]); if (loading) returnLoading...; if (error) returnError: {error.message}; return ( ); }; export default EmbeddedLink;
您現在可以在 React 應用程式中使用 EmbeddedLink 元件,如下所示:
import React from 'react'; import EmbeddedLink from './EmbeddedLink'; function App() { return (); } export default App;Link Preview Example
這將呈現所提供 URL 的預覽,及其圖像、標題和說明。
我們透過向使用者顯示適當的訊息來處理潛在的錯誤和載入狀態:
完成後,您應該可以看到如下圖所示的結果。
我更喜歡這種開發方式,而不是嵌入連結樣式,但您可以根據自己的喜好設定樣式。
免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。
Copyright© 2022 湘ICP备2022001581号-3