我是 React 新手,尝试获取从 API 返回的预签名 url(s3) 并调用预签名 URL 在浏览器上呈现 PDF。
我可以在网络选项卡上看到两个调用,一个调用返回 308,另一个调用返回 200 并带有响应。但不确定为什么我无法从响应中获取预先签名的 URL,尝试了 response.json 和 response.text。
如何从第二个调用(响应状态为 200)获取响应或如何确保只触发一个调用?
如何使用 iframe 在浏览器上渲染 pdf 或渲染 pdf 的最佳方式? 我确实尝试过使用硬编码的预签名 url,它确实下载了 pdf,但没有在 iframe 中呈现。
感谢您提前提供的帮助。下面是代码片段。
const refIframe = useRef(null)
const [data, setData] = useState(null)
useEffect(() => {
let url = "http://127.0.0.1:5000/files/1233"
const fetchData = async () => { fetch(url, {
method: 'GET',
mode: 'no-cors', // 'cors' by default
headers: {
"Access-Control-Allow-Origin": "*",
'Content-Type': 'text/html',}
}).then(response => {
return response.text()
}).then(data =>
setData(data)
);
}
fetchData();
refIframe.current.setAttribute('src', data);
}, []);
return (
<div>
<iframe ref={refIframe} allowFullScreen title={'PDF Viewer'} />
</div>
)
您的错误是在
data
之后直接访问 setData
。data
的值会改变。data
的值仍然是 null
。data
中的 then
。
const fetchData = async () => { fetch(url, {
method: 'GET',
mode: 'no-cors', // 'cors' by default
headers: {
"Access-Control-Allow-Origin": "*",
'Content-Type': 'text/html',}
}).then(response => {
return response.text()
}).then(data =>
refIframe.current.setAttribute('src', data)
);
}