在 Next.js 中显示来自 Contenful 的图像

问题描述 投票:0回答:1

我在 Next.js 应用程序中显示博客文章的图像时遇到问题。博客页面使用 Contentful 的模型来发布博客文章。

我在 types.d.ts 文件中定义了以下内容:

    import { Document } from '@contentful/rich-text-types';

    export type BlogItem = {
        fields: {
            title: string;
            slug: string;
            date: Date;
            content: Document;
            image:{}.            //left like this on purpose for now
            author:string;
        }
    }
    export type BlogItems = ReadonlyArray<BlogItem>;

    export type BlogQueryResult = {
        items: BlogItems;
    }

在我的 blog/page.tsx 中,博客文章是这样获取的:

    const getBlogEntries = async (): Promise<BlogQueryResult> => {
      const entries = await client.getEntries({ content_type: "blog" });
      return entries as unknown as BlogQueryResult; //unknown added because of a ts error

    }; 

然后在返回部分显示如下数据:

export default async function Blog() {

    const blogEntries = await getBlogEntries();
    return(
    ...
    {blogEntries.items.map((singlePost) => {
          const { slug, title, date, image, author } = singlePost.fields;
          console.log("Image field:")
          console.log(singlePost.fields.image);
    ...

上面的控制台日志给了我这个:

Image field:
{
  metadata: { tags: [] },
  sys: {
    space: { sys: [Object] },
    id: '6XUEKZLsv0hyfDCTEh2TJ7',
    type: 'Asset',
    createdAt: '2024-01-19T12:20:22.967Z',
    updatedAt: '2024-01-19T12:20:22.967Z',
    environment: { sys: [Object] },
    revision: 1,
    locale: 'en-US'
  },
  fields: {
    title: 'Entrance to the Fushimi Inari Shrine',
    description: '',
    file: {
      url:         '//images.ctfassets.net/cjo7cuugyxv4/6XUEKZLsv0hyfDCTEh2TJ7/e8aa2b53361a2db3881bfaefb0f80688/Entr ance_to_the_Fushimi_Inari_Shrine',
      details: [Object],
      fileName: 'Entrance_to_the_Fushimi_Inari_Shrine',
      contentType: 'image/jpeg'
    }
  }
}

对发布的所有代码和我描述事物的方式表示歉意。 我尝试更改类型文件中的图像字段,但一切都会导致“无法读取未定义的属性”错误,并且在线浏览解决方案我无法解决它。我还在 next.config.js 中添加了域“images.ctfassets.net”。

非常感谢任何帮助,提前致谢。

我尝试以多种方式更改图像字段,并实际匹配图像字段的控制台日志的格式,我希望从 Contentful 中检索图像 url。

image web next.js contentful
1个回答
0
投票

我有预感你不会添加

https:${image}

如果您直接在响应对象中访问链接,您将看到图像不可用,但是如果您转到:https://images.ctfassets.net/cjo7cuugyxv4/6XUEKZLsv0hyfDCTEh2TJ7/e8aa2b53361a2db3881bfaefb0f80688/Entrance_to_the_Fushimi_Inari_Sh林

是的。

© www.soinside.com 2019 - 2024. All rights reserved.