如何用Node.js配置WhatsApp、Discord分享URL时的扩展预览信息
问题解答
1. 预览卡片官方名称
你所说的这类链接预览卡片是基于 Open Graph(开放图谱,简称OG)协议 实现的社交分享富媒体卡片,也常被称为OG预览卡、社交链接预览卡。包括Discord、WhatsApp、Twitter、Telegram在内的绝大多数主流社交平台都兼容该协议,部分平台(如Twitter)也会同时兼容自定义的Twitter Cards协议,核心原理都是平台爬虫抓取目标页面<head>标签内的特定meta标签,提取内容生成预览卡片。
参考预览效果:

2. Express.js 实现方案
实现原理
在服务端返回的HTML页面的<head>部分插入符合Open Graph协议的meta标签,社交平台的爬虫访问链接时会自动读取这些标签内容生成预览卡片。
实现步骤
第一步:初始化项目
执行以下命令安装依赖:
npm init -y npm install express ejs
第二步:编写Express服务代码
新建app.js文件,内容如下:
const express = require('express') const app = express() const port = 3000 // 配置ejs模板引擎 app.set('view engine', 'ejs') // 静态资源托管,比如存放预览图片的public目录 app.use(express.static('public')) // 示例路由:首页 app.get('/', (req, res) => { // 可以根据业务逻辑动态传入OG标签内容,比如从数据库查询对应页面的信息 const ogInfo = { title: '示例页面标题', description: '这是页面的描述内容,会显示在预览卡片的标题下方', image: 'https://你的域名.com/preview.jpg', // 必须用绝对路径 url: 'https://你的域名.com' } res.render('index', { ogInfo }) }) // 示例路由:详情页,可动态生成对应内容的OG标签 app.get('/detail/:id', (req, res) => { const { id } = req.params // 模拟根据ID查询数据库拿到对应内容信息 const ogInfo = { title: `详情页${id}的标题`, description: `这是ID为${id}的详情页描述`, image: 'https://你的域名.com/detail-preview.jpg', url: `https://你的域名.com/detail/${id}` } res.render('index', { ogInfo }) }) app.listen(port, () => { console.log(`服务运行在 http://localhost:${port}`) })
第三步:编写模板文件
新建views/index.ejs文件,内容如下:
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title><%= ogInfo.title %></title> <!-- Open Graph核心标签 --> <meta property="og:title" content="<%= ogInfo.title %>"> <meta property="og:description" content="<%= ogInfo.description %>"> <meta property="og:image" content="<%= ogInfo.image %>"> <meta property="og:url" content="<%= ogInfo.url %>"> <meta property="og:type" content="website"> <!-- 可选:适配Twitter的卡片标签 --> <meta name="twitter:card" content="summary_large_image"> <meta name="twitter:title" content="<%= ogInfo.title %>"> <meta name="twitter:description" content="<%= ogInfo.description %>"> <meta name="twitter:image" content="<%= ogInfo.image %>"> </head> <body> <!-- 页面正常内容 --> <h1><%= ogInfo.title %></h1> <p><%= ogInfo.description %></p> </body> </html>
注意事项
- 所有OG标签用到的资源路径(图片、页面URL)必须使用完整的绝对路径,不能使用相对路径,社交平台爬虫无法识别相对路径
- 如果你的项目是前后端分离的单页应用(React/Vue等),可以通过服务端渲染(SSR)、预渲染、或者专门的爬虫路由中间件的方式返回带OG标签的内容,避免爬虫抓取到空的head内容
- 可以使用各大平台的官方预览检测工具验证配置是否正确
内容的提问来源于stack exchange,提问作者MasonHuman_
相关产品推荐
相关产品推荐

