构建 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