reactjs - 如何从 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 中获取图片?
解决方案
推荐阅读
- python - 有没有办法用 c++ Gsoap 客户端调用 python soap spyne 服务器?
- c++ - 用于 SPI 通信的互斥锁
- c# - 无法连接kafka集群时也不例外
- php - 如果用户不注销并简单地关闭选项卡,则用户可以通过 URL 访问页面
- javascript - 使用 TypeScript 动态加载 React 组件
- grep - 查找包含某个字符串的多个文件并列出不包含该字符串的文件
- javascript - 如何获取当前连接的所有活动视频设备?
- kotlin - 如何不在函数中传递一些参数
- php - 如何将php变量绑定到mysql查询
- android - 我想知道我的地图(ImageView)的哪个特定区域被点击了