Next.js代码开发环境正常 部署Vercel后Cloudinary图片无法加载
直接报错原因修复
你部署后无法渲染的直接原因是浏览器的混合内容拦截:Vercel 站点使用 HTTPS 协议加载,但你代码中请求 Cloudinary 接口用的是 HTTP 协议,被浏览器安全策略拦截了。
只需要把请求地址的协议头改成 HTTPS 即可临时解决问题:
把 axios.get('http://res.cloudinary.com/delpknfnx/image/list/something.json')
修改为 axios.get('https://res.cloudinary.com/delpknfnx/image/list/something.json')
更优方案:使用 getStaticProps 实现静态生成
用 getStaticProps 可以在构建阶段就把图片数据拉取到,直接生成静态页面,不需要用户访问时再在客户端发请求,加载速度更快,也不会暴露接口请求逻辑。
修改后的完整代码如下:
import React from 'react' import { CloudinaryContext, Image, Transformation } from 'cloudinary-react' import axios from 'axios' import Default from '@components/layouts/default' import styles from '@styles/modules/gallery.module.css' // 改为函数组件,接收getStaticProps传入的images参数 const Gallery = ({ images }) => { return ( <Default pageTitle="Gallery" > <article className="wrapper"> <h1>See our latest on the job snaps!</h1> <CloudinaryContext cloudName="delpknfnx"> <div className={styles.gallery}> {images.map((data, index) => ( <div key={index}> <h2>{data.context.custom.caption}</h2> <Image publicId={data.public_id} alt={data.context.custom.caption} dpr="auto" responsive width="auto" responsiveUseBreakpoints="true" loading="lazy" > <Transformation quality="auto" fetchFormat="auto" /> </Image> <p>{data.context.custom.alt}</p> </div> ))} </div> </CloudinaryContext> </article> </Default> ); } // 静态数据获取方法,Next.js构建时会自动执行 export async function getStaticProps() { const res = await axios.get('https://res.cloudinary.com/delpknfnx/image/list/something.json') const images = res.data.resources return { props: { images }, // 可选:如果图片会定期更新,可以加revalidate配置开启增量静态再生,单位是秒 revalidate: 86400 // 每天自动更新一次数据 } } export default Gallery
注意事项
- 如果你的 Cloudinary 资源访问需要鉴权,不要把密钥直接写在客户端代码里,
getStaticProps是服务端执行的逻辑,敏感信息可以存在 Vercel 的环境变量里调用,不会泄露到客户端。 - 加了
revalidate配置后,不需要每次更新图片都重新部署项目,Next.js 会自动在后台拉取最新数据更新静态页面。
内容的提问来源于stack exchange,提问作者jk2908
相关产品推荐
相关产品推荐

