使用Unsplash API+EJS渲染图片报错‘Couldn't find photo’求助
问题:Unsplash API结合EJS渲染图片时出现"Couldn't find photo"错误
我是编程新手,尝试用Unsplash API配合EJS渲染图片,但一直出现Couldn't find photo错误。我怀疑问题出在图片ID上,不知道怎么添加动态photo ID,也想排查是否有其他错误。
EJS模板代码
<%- include('header'); -%> <h1>My photo</h1> <img src='<%= image %>' /> <%- include('footer'); -%>
Node.js后端代码
import express from 'express' import { createApi } from 'unsplash-js'; import nodeFetch from 'node-fetch'; import https from 'https'; import ejs from 'ejs'; const app = express(); app.set('view engine', 'ejs'); const unsplash = createApi({ accessKey: 'jSkL3CYPolL5G2mk8k28YJa8ITOcobvtWWP_2lRT_Z0', fetch: nodeFetch, }); const url = "https://api.unsplash.com/photos/?client_id=jSkL3CYPolL5G2mk8k28YJa8ITOcobvtWWP_2lRT_Z0" unsplash.photos.get({ photoId: 'pXhwzz1JtQU' }).then(result => { if (result.errors) { console.log('error occurred: ', result.errors[0]); } else { const photo = result.response; console.log(photo); app.get("/", function(req, res){ res.render("home", {image: photo}); }); } }); unsplash.photos.getRandom({}); unsplash.photos.getRandom({ count: 10, }); unsplash.photos.getRandom({ collectionIds: ['abc123'], topicIds: ['def456'], featured: true, username: 'naoufal', query: 'dog', count: 1, }); app.listen(3000, function() { console.log("Server started on port 3000"); });
问题排查与修复
1. 核心错误点解析
- 路由注册时机颠倒:把
app.get("/")放在API回调里,导致只有API请求成功后路由才生效。如果API失败,访问根路径会直接404,逻辑完全错误。 - 图片地址传递错误:
photo是Unsplash返回的完整对象,直接传给EJS的image变量,会让<img>的src变成对象字符串,根本不是有效URL。需要取photo.urls.regular这类具体的图片链接字段。 - 冗余无效API调用:后面三次
unsplash.photos.getRandom调用没有处理结果,纯浪费API请求额度,直接删除即可。
2. 动态Photo ID实现方法
通过URL参数接收动态ID,比如访问/photo/xxx展示对应图片:
- 定义带参数的路由:
app.get("/photo/:photoId", ...) - 从
req.params.photoId获取传入的ID,再调用Unsplash API
3. 修复后的完整代码
后端Node.js代码
import express from 'express' import { createApi } from 'unsplash-js'; import nodeFetch from 'node-fetch'; import ejs from 'ejs'; const app = express(); app.set('view engine', 'ejs'); const unsplash = createApi({ accessKey: 'jSkL3CYPolL5G2mk8k28YJa8ITOcobvtWWP_2lRT_Z0', fetch: nodeFetch, }); // 根路由:展示示例图片(可选) app.get("/", async function(req, res) { try { const result = await unsplash.photos.get({ photoId: 'pXhwzz1JtQU' }); if (result.errors) { return res.send('获取图片失败:' + result.errors[0]); } const photoUrl = result.response.urls.regular; res.render("home", { image: photoUrl }); } catch (err) { res.send('服务器错误:' + err.message); } }); // 动态ID路由:根据URL参数展示对应图片 app.get("/photo/:photoId", async function(req, res) { const photoId = req.params.photoId; try { const result = await unsplash.photos.get({ photoId }); if (result.errors) { return res.send('无法找到图片:' + result.errors[0]); } const photoUrl = result.response.urls.regular; res.render("home", { image: photoUrl }); } catch (err) { res.send('服务器错误:' + err.message); } }); app.listen(3000, function() { console.log("Server started on port 3000"); });
EJS模板代码(仅补充alt属性优化体验)
<%- include('header'); -%> <h1>My photo</h1> <img src='<%= image %>' alt='Unsplash Photo' /> <%- include('footer'); -%>
额外注意事项
- Unsplash API有请求次数限制,开发阶段别频繁调用,避免被限流。
- 新增的
try/catch能捕获异步错误,同时处理API返回的错误信息,方便调试。 - Unsplash返回的
urls包含不同尺寸链接(thumb/regular/full),可根据需求选择。
内容的提问来源于stack exchange,提问作者Garry
相关产品推荐
相关产品推荐

