如何在Facebook / Linkedin中创build链接预览

我正在创build一个web应用程序使用平均stack.It将有一个input框,用户可以写任何将存储在mongo分贝,然后使用angular度显示的任何东西。 这与新闻源相似。 所以用户甚至可以input我成功从文本中提取的url,并将其转换为链接。 我想做点什么,如Facebook和LinkedIn做什么..

在这里输入图像描述

刮到给定的url,并显示其主要图像和标题,但这应该做angular度而不去节点。

有没有办法在浏览器中做到这一点? 有了这个节点,我正在使用node.io

经过几个小时的谷歌search,我自己find了答案..已经有一个问题是否有开放源代码的“链接预览”文本和图标,如在Facebook? 。 所以我们可以使用这个链接http://api.embed.ly/1/oembed?url=YOUR-URL通过http GET,我们得到的JSON格式的meta标签..我写了我自己的代码使用JSdom ,这里去码…

服务器端代码:

app.post( '/scrapUrl/', function( req, res ) { var jsdom = require( 'jsdom' ); var jsonRes = {}; jsdom.env( { url: req.body.url, scripts: [ "http://code.jquery.com/jquery.js" ], done: function( error, window ) { var $ = window.$; $( 'meta' ).each( function() { var name = $( this ).attr( 'property' ); var value = $( this ).attr( 'content' ); if ( name ) { jsonRes[ name.slice( 3 ) ] = value; console.log( name + ": " + value ); } } ); res.send( jsonRes ); } } ); } ); 

和angular码

 $http.post( '/scrapUrl/', { url: url //send the url U need to scrape } ).then( function( res ) { console.log(res.data)//U get the meta tags as json object }); 

一旦你得到了JSON对象,你可以用你想要的任何风格来显示它。

如果有人仍然在寻找答案,我build议你看http://ogp.me 。 它适用于电报信使,Facebook,Discord等。

我在这个项目中使用了一个框架https://github.com/pBouillon/Sublime_text_snippets/blob/master/html_core.sublime-snippet

 <head> <!-- open graph --> <!-- Informations --> <meta property="og:description" content="OPEN_GRAPH_DESCRIPTION" /> <meta property="og:title" content="OPEN_GRAPH_TITLE" /> <meta property="og:type" content="website" /> <meta property="og:url" content="WEBSITE_URL" /> <!-- Image --> <meta property="og:image" content="URL_TO_IMAGE" /> <meta property="og:image:alt" content="Website icon" /> <meta property="og:image:height" content="80" /> <meta property="og:image:secure_url" content="URL_TO_IMAGE" /> <meta property="og:image:type" content="image/png" /> <meta property="og:image:width" content="80" /> <meta property="og:locale" content="en_GB" /> </head>