programing

Vue JS에서 열린 그래프 메타 태그가 이미지를 표시하지 않음

nicescript 2022. 7. 14. 21:31
반응형

Vue JS에서 열린 그래프 메타 태그가 이미지를 표시하지 않음

블로그를 디자인하고 있는데, 소셜 네트워크에 공유할 때 미리보기 이미지가 Medium의 투고와 같이 표시되도록 하고 싶습니다.

<meta property="og:image" content="https://medium.com/js-dojo/getting-your-head-around-vue-js-scoped-slots-281bf82a1e4e"/>

webpack 및 vue-meta와 함께 vuejs2를 사용하여 게시물의 동적 이미지를 변경합니다.하지만 페이스북은 index.html에 넣어도 작동이 되지 않습니다.

기사는 Server Side Rendered를 사용할 필요가 있다고 하는 매체에서 찾을 수 있지만, 기본적인 구성을 가진 완전 설계 프로젝트에서 문제를 해결하는 프로젝트로 이행하는 방법은 나와 있지 않습니다.이미 아키텍처가 다르고 참조가 없습니다.

여기 내 코드 vue-voice가 있습니다.

metaInfo () {
  return {
    title: '41devs | blog',
    titleTemplate: '%s - le titre',
    meta: [
      {name: 'viewport', content: 'user-scalable=no'},
      {property: 'og:title', content: 'title'},
      {property: 'og:type', content: 'article'},
      {property: 'og:url', content: 'http://c5e3b0ec.ngrok.io/blog/s'},// here it is just ngrok for my test
      {property: 'og:description', content: 'description'},
      {property: 'og:image', content: 'https://firebasestorage.googleapis.com/v0/b/dev-blog-2503f.appspot.com/o/postsStorage%2F-KxXdvvLqDHBcxdUfLgn%2Fonfleck?alt=media&token=24a9bf5b-dce2-46e8-b175-fb63f7501c98'},
      {property: 'twitter:image:src', content: 'https://firebasestorage.googleapis.com/v0/b/dev-blog-2503f.appspot.com/o/postsStorage%2F-KxXdvvLqDHBcxdUfLgn%2Fonfleck?alt=media&token=24a9bf5b-dce2-46e8-b175-fb63f7501c98'},
      {property: 'og:image:width', content: '1000'},
      {property: 'og:site_name', content: '41devs | blog'}
    ]
  }
}

페이스북이 메타 데이터를 찾기 위해 당신의 페이지를 체크할 때, 그들은 당신의 Javascript를 실행하지 않습니다.Vue는 실행되지 않으며 태그는 교체되지 않습니다.이것은 페이스북 크롤러의 한계이다.

즉, Vue의 서버 측 렌더링이든 다른 방법으로든 서버 수준에서 태그를 렌더링해야 합니다(실행하고 있는 서버의 타입은 알 수 없습니다).단, 최종적으로는 서버 응답에 이 값을 하드 코드화할 수 있어야 합니다.그렇지 않으면 Facebook에 표시되지 않습니다.

제가 이 문제를 해결한 방법은 URL 경로를 해석하고 Cheerio 모듈을 사용하여 메타 태그를 동적으로 업데이트하는 미들웨어를 만드는 것이었습니다.

OG 메타 태그 정보 파일:

const products = [
  {
    id: 111111111,
    title: 'Corporate Fat Cat',
    ogImage: 'https://cdn.com/corporate.jpg',
    description: 'The fat cats in Washington don’t even look this good'
  },
  {
    id: 222222222,
    title: 'Gangsta Cat',
    ogImage: 'https://cdn.com/gangsta.jpg',
    description: 'That’s how we roll'
  },
  {
    id: 333333333,
    title: 'Mechanic Cat',
    ogImage: 'https://cdn.com/mechanic.jpg',
    description: 'I have no idea what I’m doing.'
  }
];

미들웨어:

app.use('/*', (req, res, next) => {
  if (/^\/api\//.test(req.originalUrl)) next();
  else if (/\/item\//.test(req.originalUrl)) updateMetaTags(req, res);
  else res.sendFile(`${__dirname}/client/dist/index.html`);
});

updateMetaTags 함수:

async function updateMetaTags(req, res) {

  // Get and parse products array from app src
  const productsSrc = `${__dirname}/client/src/products.js`;
  const productsText = await fs.promises.readFile(productsSrc);
  const productsArr = JSON.parse(productsText);

  // Retrieve product object that includes the current URL item id
  const productID = (req.originalUrl.match(/\d{9}/) || [])[0];
  const productObj = productsArr.find(prod => prod.id == productID);

  // Update the meta tag properties in the built bundle w/ Cheerio
  const baseSrc = `${__dirname}/client//dist/index.html`;
  const baseHTML = await fs.promises.readFile(baseSrc);
  const $base = $(baseHTML);
  const $url = $base.find('meta[property=og\\:url]');
  const $title = $base.find('meta[property=og\\:title]');
  const $image = $base.find('meta[property=og\\:image]');
  $desc = $base.find('meta[property=og\\:description]');

  $url.attr('content', `https://${req.get('host')}${req.originalUrl}`);
  $title.attr('content', productObj.title);
  $image.attr('content', productObj.ogImage);
  $desc.attr('content', productObj.description);

  // Send the modified HTML as the response
  res.send($.html($base));
}

나는 이 블로그 투고에서 더 자세히 접근했다.

제목과 titleTemplate의 구조가 잘못되었습니다.

return {
    title: 'Le titre',           // Set a current title of page
    titleTemplate: '%s - 41devs blog', // Name of your blog/website,
                                       // Title is now "Le titre - 41devs blog"
    meta: [ ...
    ]
}

구글 https://support.google.com/webmasters/answer/79812?hl=en에서 최고의 SEO를 달성했습니다.

언급URL : https://stackoverflow.com/questions/47639690/open-graph-meta-tags-in-vue-js-dont-show-image

반응형