首页 > 解决方案 > 如何从 Ghost(内容 API)获取图像到 Next.js?

问题描述

类似的帖子在这里

使用 vercel 进行前端的最终部署,连接到 Heroku 的 Ghost CMS 后端。

我正在尝试从 Ghost CMS API 获取图像,在他们使用的文档中:

"feature_image": "https://static.ghost.org/v3.0.0/images/welcome-to-ghost.png"

或者

"og_image": null,

我假设这两个值都是字符串。

但是这些都没有获取在本节中发布在 ghost 上的图像(当然,我实际上会将 png 文件拖放到那里,只是显示图片以供参考):

在此处输入图像描述

在 ghost CMS 添加帖子页面的右上角:

在此处输入图像描述

这是我的代码:

import { useRouter } from "next/dist/client/router";
import Link from "next/link";
import { useState } from "react";

const { BLOG_URL, CONTENT_API_KEY } = process.env;

async function getPost(slug: string) {
  const res = await fetch(
    `${BLOG_URL}/ghost/api/v3/content/posts/slug/${slug}?key=${CONTENT_API_KEY}&fields=title,slug,html`
  ).then((res) => res.json());
  console.log(res);

  const posts = res.posts;

  return posts[0];
}

// Ghost CMS Request
export const getStaticProps = async ({ params }) => {
  const post = await getPost(params.slug);
  return {
    props: { post },
  };
};

export const getStaticPaths = () => {
  // paths -> slugs which are allowed
  // fallback -> give getStaticProps a chance to get something
  return {
    paths: [],
    fallback: true,
  };
};

type Post = {
  title: string;
  html: string;
  slug: string;
  og_image: string;
  feature_image: string;
};

const Post: React.FC<{ post: Post }> = (props) => {
  const { post } = props;
  const [enableLoadComments, setEnableLoadComments] = useState<boolean>(true);

  const router = useRouter();

  if (router.isFallback) {
    return <h1>Loading . . .</h1>;
  }

  function loadComments() {
    setEnableLoadComments(false);
    // load disqus
    (window as any).disqus_config = function () {
      this.page.url = window.location.href;
      this.page.identifier = post.slug;
    };

    const script = document.createElement("script");
    script.src = "https://toeyristafitness.disqus.com/embed.js";
    script.setAttribute("data-timestamp", Date.now().toString());

    document.body.appendChild(script);
  }

  return (
    <div>
      <p>
        <Link href="/">
          <a>Go back</a>
        </Link>
      </p>
      <h1>{post.title}</h1>
      <>{post.og_image}</>
      <>{post.feature_image}</>
      <div dangerouslySetInnerHTML={{ __html: post.html }}></div>

      {enableLoadComments && <p onClick={loadComments}>Load Comments</p>}

      <div id="disqus_thread"></div>
    </div>
  );
};

export default Post;

有没有其他方法可以尝试从 Ghost CMS API 中获取图片?

标签: reactjsnext.jsghost-blog

解决方案


推荐阅读