티스토리 뷰

reactJS

open-graph-scraper 사용하기

코딩하는 둥아 2022. 1. 26. 13:34
728x90

✅  React + Nodejs 프로젝트 생성 참고 링크

 

📞 React + Node.js(Express) 연동하기 (1)

💡 Express ? - Express.js, 또는 Express는 Node.js를 위한 웹 프레임워크의 하나이다. javascript를 이용하여 프론트와 함께 백엔드를 구축하여 서버-클라이언트를 모두 개발할 수 있다. 참고 : Express 개념정

baegofda.tistory.com

위의 React + Node.js 연동하기 (1), (2) 편을 참고하여 기본 환경을 세팅하고 시작합니다.

 

✅  og tag란? (meta tag, open graph)

카카오톡에 링크를 보냈을때 아래와 같이 링크의 대표 이미지와 대표 설명이 나오는 것을 확인할 수 있습니다.

Github 대표 이미지와 설명

og tag란 콘텐츠의 요약 내용이 SNS에 게시되는데 최적화된 데이터를 가지고 갈 수 있도록 설정하는 것입니다.

웹사이트의 head안에 들어가는 meta 태그에 property="og:"로 시작하는 태그들이 설정을 돕습니다.

<meta property="og:type" content="website">
<meta property="og:url" content="https://example.com/page.html">
<meta property="og:title" content="Content Title">
<meta property="og:image" content="https://example.com/image.jpg">
<meta property="og:description" content="Description Here">
<meta property="og:site_name" content="Site Name">
<meta property="og:locale" content="en_US">
<!-- 다음의 태그는 필수는 아니지만, 포함하는 것을 추천함 -->
<meta property="og:image:width" content="1200">
<meta property="og:image:height" content="630">

 

 

웹페이지에서 특정 url이 가진 og 태그 정보를 가져오는 방법을 찾아보다가 "open-graph-scrapper"라는 패키지를 발견했습니다. 그래서 이 포스팅에서는 open-graph-scrpper를 사용하여 react와 nodejs 환경에서 웹페이지의 메타 태그 정보를 가져와 웹사이트의 대표 이미지와 설명을 가져오는 것을 해보겠습니다😄

 

 

 

 

위의 포스팅을 따라하여 meta-tag라는 프로젝트를 생성하였고, express서버가 정상적으로 구동이 되는 환경을 만들어두었습니다.

프로젝트의 디렉토리 구조는 아래와 같습니다.

프로젝트 구조

✅ test.js 수정하기

저희는 test.js에서 open-graph-scrpper를 사용하여 url에 대한 메타태그 정보를 가져올 것입니다.

  • options의 url에는 정보를 얻고자 하는 url을 입력합니다.
  • org를 함수에 options를 파라미터로 넘겨 결과값인 result에 원하는 정보를 반환받습니다.
const express = require("express");
const router = express.Router();
const ogs = require("open-graph-scraper");
let options = {
    url: "https://github.com/",
    timeout: 4000
}

router.get("/", (req, res) => {
    ogs(options, function(error, result) {
        console.log("error: ", error);
        console.log("results: ", result);
        res.send({results: result});
    })
});

module.exports = router;

아래는 result값을 console에 출력한 결과값입니다.

github 홈페이지 같은 경우 ogTitle, ogImage, ogSiteName... 등 다양한 메타 정보를 가지고 있습니다.

 

✅ App.js 수정하기

  • callApi function에서 axios를 이용하여 /api로 request를 보냅니다.
  • 설정해놓은 setupProxy 설정으로 인해 /api로 시작되는 API의 요청이 들어오면 "http://localhost:포트번호/api" 로 맵핑되어 호출되게 됩니다.
  • 저는 5001번 포트를 사용하기 때문에 http://localhost:5001/api로 맵핑되어 test.js의 api를 호출하게 되고, 위에서 확인한 og tag 정보를 callApi의 결과값으로 받게 됩니다.
  • callApi의 정보를 받아서 화면에 적절하게 보여주면 태그 정보 가져오기 성공!
import logo from './logo.svg';
import './App.css';
import axios from "axios";
import {useEffect, useState} from "react";

function App() {
  const [result, setResult] = useState(null);

  const callApi = async() => {
    axios.get("/api").then((res) => {
      console.log(res.data.results);
      setResult(res.data.results)
    });
  };

  useEffect(() => {
    callApi();
  }, []);

  return (
    <div>
      <h1>Og Tag 가져오기</h1>
      <div>
        {result && result.ogTitle && <p>{result.ogTitle}</p>}
        {result && result.ogImage && <img src={result.ogImage.url} width="350" alt="site"/>}
        {result && result.ogSiteName && <p>{result.ogSiteName}</p>}
        {result && result.ogDescription && <p>{result.ogDescription}</p>}
      </div>
    </div>
  );
}

export default App;

 

✅ 결과화면

App.js 화면

원하는 웹사이트의 og tag 정보를 가져와서 화면에 보여주는 작업이 끝났습니다!

해당 정보를 예쁜 UI에 맞게 보여주면 될 것 같습니다😊

728x90
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함