reactjs - 尝试从外部 API 显示图像时出错(JSON 中的意外令牌)
问题描述
我正在尝试显示来自外部 api 的图像。但我只得到错误
Uncaught (in promise) SyntaxError: Unexpected token � in JSON at position 0"
我猜问号意味着它是身份不明的东西......
无论如何,我遵循了有关如何显示图像的 api 文档。要从寄存器中获取图像,我使用端点文章文件连接来获取我在存档端点中使用的 FileId 来获取图像。
这是两个端点的文档:
- https://developer.fortnox.se/documentation/resources/article-file-connections/
- https://developer.fortnox.se/documentation/resources/archive/
当我使用postmanitemId
和FileId
in 尝试端点时,它可以工作并显示图像,但不在我的代码中。所以我在代码中做错了。但它是什么?
我认为这是我SingleProductImage
页面的问题,有人可以帮忙吗?
我正在使用 React 挂钩来获取 api,这是我的代码:
export const SingleProductImage = (props) => {
const [articleImg, setArticleImg] = useState('')
console.log(articleImg) // when I console this nothing shows
console.log(props.fileid) // when I console this the fileid shows
useEffect(() => {
fetch('https://cors-anywhere.herokuapp.com/https://api.fortnox.se/3/archive/${props.fileid}', {
method: 'GET',
headers: {
'Content-Type': 'application/json',
Accept: 'application/json',
'Access-Token': accessToken,
'Client-Secret': clientSecret
}
})
.then((res) => res.json())
.then((data) => {
setArticleImg(data)
console.log(data)
})
}, [articleImg])
return (
<div>
<img src={articleImg} alt="product" />
</div>
)
}
单品图片页面
export const SingleProductPage = () => {
const { itemId } = useParams()
const [article, setArticle] = useState([])
const [articleImg, setArticleImg] = useState('')
const [fileId, setFileId] = useState([])
useEffect(() => {
fetch(`https://cors-anywhere.herokuapp.com/https://api.fortnox.se/3/articles/${itemId}`, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
Accept: 'application/json',
'Access-Token': accessToken,
'Client-Secret': clientSecret
}
})
.then((res) => res.json())
.then((data) => {
console.log(data)
setArticle(data.Article)
console.log(data)
})
}, [itemId])
useEffect(() => {
fetch(`https://cors-anywhere.herokuapp.com/https://api.fortnox.se/3/articlefileconnections/?articlenumber=${itemId}`, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
Accept: 'application/json',
'Access-Token': accessToken,
'Client-Secret': clientSecret
}
})
.then((res) => res.json())
.then((data) => {
setFileId(data.ArticleFileConnections[0].FileId)
console.log(data.ArticleFileConnections[0].FileId)
})
}, [itemId])
return (
<div>
<SingleProductImage fileid={fileId} />
</div>
)
解决方案
您正在.json()
对 api 返回的整个对象进行强制转换。而是只取 url,你的错误应该消失
...
.then((res)=> setArticleImg(res.url))
.catch((err)=> console.log(err))
推荐阅读
- android - LOCAL_CFLAGS := -fstack-protector-all 不起作用
- javascript - 如何防止打字稿在编译文件中添加导入
- xml - FORG0001:日期无效。非数字组件
- flutter - Flutter 中用于启动画面的视频播放器
- docker - 在 Gitlab-Runner (Docker Executor) 中使用数据时遇到问题
- javascript - 为什么我的 collRect 数组没有得到项目?
- javascript - 如何使用 alpine js 使按钮集中在单击按钮上?
- arrays - 从 Google Sheet API v4 追加数据不再起作用
- java - Spring Boot:无法为@Cacheable 设置过期时间
- openapi - 如何在 OpenAPI 中引用响应组件?