首页 > 解决方案 > 尝试从外部 API 显示图像时出错(JSON 中的意外令牌)

问题描述

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

Uncaught (in promise) SyntaxError: Unexpected token � in JSON at position 0"

我猜问号意味着它是身份不明的东西......

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

这是两个端点的文档:

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

我认为这是我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>
)

标签: reactjspromisereact-hooksuse-effect

解决方案


您正在.json()对 api 返回的整个对象进行强制转换。而是只取 url,你的错误应该消失

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


推荐阅读