【发布时间】:2020-10-22 20:44:44
【问题描述】:
我正在尝试显示来自外部 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/
当我在邮递员中尝试使用itemId 和FileId 的端点时,它可以工作并显示图像,但不在我的代码中。所以我在代码中做错了。但它是什么?
我认为这是我的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>
)
【问题讨论】:
-
在这部分代码中添加
console.log(res).then((res) => res.json())而不是执行 .json 并查看响应是什么。没有仔细阅读您的 api 提供者的文档,但它可能不是您所期望的,即只是 url -
我按照你的建议添加了 console.log(res),我想我得到了我期望的响应,它是我在邮递员中尝试的具有正确 fileId 的 url。
-
看起来像这样:响应{type:“cors”,url:“cors-anywhere.herokuapp.com/https://api.fo…se/3/archive/8c05c536-c110-402d-82da-60f25f6b0e1c”,重定向:false,状态:200,好的:是的,……}
-
如您所见,您获得的不仅仅是 URL,而是包含其他信息的对象。然后你需要使用 res.url 而不是整个 res,因为你的 url 存储在 'url' 键下,它应该可以解决你的错误。
标签: reactjs promise react-hooks use-effect