构建 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) return <div>loading...</div>; if (error) return <div>error: {error.message}</div>; return ( <div classname="embedded-link border-2 p-5 my-3 border-neutral-800"> {imageurl && <img src={imageurl} alt={title} classname="cover-image max-w-50 w-auto h-auto" />} <a href={url} target="_blank" rel="noopener noreferrer" classname="text-indigo-500 underline font-bold text-2xl"> {title && <h3>{title}</h3>} </a> {!imageurl && !title && <p>no preview available</p>} <p classname="my-3">{description}</p> <p classname="text-slate-500">{url}</p> </div> ); }; export default embeddedlink;
您现在可以在 react 应用程序中使用 embeddedlink 组件,如下所示:
import React from 'react'; import EmbeddedLink from './EmbeddedLink'; function App() { return ( <div className="App"> <h1>Link Preview Example</h1> <EmbeddedLink url="https://example.com" /> </div> ); } export default App;
这将呈现所提供 url 的预览,及其图像、标题和描述。
我们通过向用户显示适当的消息来处理潜在的错误和加载状态:
完成后,您应该能够看到如下图所示的结果。
相对于嵌入式链接样式,我更喜欢此开发,但您可以根据自己的喜好设置其样式。