尝试从外部API显示图像时出错(意外的令牌�在JSON中)



我正在尝试显示来自外部api的图像。但我只得到错误

未捕获(在promise中(SyntaxError:意外的令牌�在位置0"的JSON中;

我想问号的意思是它是某种未识别的东西。。。

无论如何,我遵循了关于如何显示图像的api文档。为了从寄存器中获取图像,我使用端点文章文件连接来获取FileId,我在存档端点中使用该FileId来获取图像。

以下是两个端点的文档:

  • https://developer.fortnox.se/documentation/resources/article-file-connections/
  • https://developer.fortnox.se/documentation/resources/archive/

当我在poster中尝试使用itemIdFileId的端点时,它可以工作并显示图像,但不在我的代码中。所以代码中有我做错的地方。但它是什么?

我觉得我的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>
)
}

SingleProductImage页面

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>
)

您正在对api返回的整个对象强制转换.json()。相反,只采取网址和你的错误应该消失

... 
.then((res)=> setArticleImg(res.url))
.catch((err)=> console.log(err))

最新更新