簡體   English   中英

React使用fetch從api獲取圖像

[英]React get image from api using fetch

我需要使用 fetch api 獲取圖像。 我的同事說對服務器的調用應該返回一個base64字符串來顯示圖像。 圖像需要進行身份驗證,我不能只使用它的 url。 這就是我所擁有的:

fetch(`${apiUrl}filestore/${logo.name}`, {
        
        .then(res => console.log(res)
        

我不太確定如何獲取 base64 字符串。 顯然我沒有正確使用 fetch 。 這是控制台中顯示的內容,![屏幕截圖][1]

嘗試將 res 格式化為 json。 然后檢查res。

 fetch(`${apiUrl}filestore/${logo.name}`, { method: 'GET', headers: { Authorization: JSON.parse(localStorage.getItem('Hidden')) ? `Bearer ${JSON.parse(localStorage.getItem('Hidden')).access_token}` : '', }, }) .then(res => return res.json()) .then(res => console.log(res))

這是 Fetch API 的 mdn 文檔的鏈接 - https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

fetch('http://example.com/movies.json')
 .then(response => response.json()) 
 .then(data => console.log(data))
 .catch(e => console.log("error", e);

考慮到您的響應是 JSON 類型 - 查找支持的正文實例的鏈接 - https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch#Body

試試 console.log(typeof response); 找出您的響應類型是什么,以便您可以在 .then(response => response.json() 或 response.text() 等中設置正文實例,)

確保你也捕捉到錯誤。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM