如何从快速后端服务器获取图像并将其显示到 React js 前端? [英] How to Fetch and Display an Image from an express backend server to a React js frontend?
问题描述
我正在尝试从快速后端获取图像并将它们显示在 react js 前端中.我怎样才能完美地做到这一点?
我尝试获取保存在名为Backup"的后端文件夹中的图像,并将它们显示回 react js 前端中的用户.我已经使用 axios 尝试过这个,但仍然得到一个无效的图像而不是正确的图像.
下面是我在前端的获取请求.
fetchImages = () =>{const imageName = 'garande.png'const url = `http://localhost:5000/fetchImage/${imageName}`axios.get(url, {responseType: 'blob'}).then(res => {返回(<img src={res.data} alt="试用"/>)}}
这是我在后端的 server.js 文件中的内容
app.get('/fetchImage/:file(*)', (req, res) => {让文件 = req.params.file;let fileLocation = path.join('../Backup/images/', file);//res.send({image: fileLocation});res.sendFile(`${fileLocation}`)})
我希望图像显示在用户页面中.谢谢.
这对我有用:
导出异步函数 get(url: string) {尝试 {const response = await fetch(url, {method: 'GET',//*GET、POST、PUT、DELETE 等.模式:'cors',//无cors,*cors,同源缓存:'无缓存',//*默认,无缓存,重新加载,强制缓存,仅当缓存标题:{'内容类型':'图像/jpeg'}})const blob = 等待 response.blob()返回 [URL.createObjectURL(blob), null];}捕捉(错误){console.error(`get: 发生错误 ${error}`);返回 [空,错误]}}函数 foo(props: any) {const [screenShot, setScreenshot] = useState(undefined)const url = props.urluseEffect(() => {异步函数 fetchData() {//你可以在这里等待const [响应,错误] = await get(url)如果(错误)日志(错误)别的 {日志(`得到响应 ${response}`)设置截图(响应)}}取数据();}, [网址])返回 <img src={screenShot} className=屏幕截图"alt=显示屏幕截图";/>}
I'm trying to fetch images from an express backend and display them in the react js frontend. How can I achieve this perfectly?
I have tried to fetch the images saved in my backend folder named "Backup" and display them back to the user in the react js frontend. I have tried this using axios but still am getting an invalid image instead of the correct image.
Below is my fetch request in the frontend.
fetchImages = () => {
const imageName = 'garande.png'
const url = `http://localhost:5000/fetchImage/${imageName}`
axios.get(url, {responseType: 'blob'})
.then(res => {
return(
<img src={res.data} alt="trial" />
)
}
}
And this what I have in the server.js file in the backend
app.get('/fetchImage/:file(*)', (req, res) => {
let file = req.params.file;
let fileLocation = path.join('../Backup/images/', file);
//res.send({image: fileLocation});
res.sendFile(`${fileLocation}`)
})
I expect the Image to show up in the users page. Thanks.
This worked for me:
export async function get(url: string) {
try {
const response = await fetch(url, {
method: 'GET', // *GET, POST, PUT, DELETE, etc.
mode: 'cors', // no-cors, *cors, same-origin
cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
headers: {
'Content-Type': 'image/jpeg'
}
})
const blob = await response.blob()
return [URL.createObjectURL(blob), null];
}
catch (error) {
console.error(`get: error occurred ${error}`);
return [null, error]
}
}
function foo(props: any) {
const [screenShot, setScreenshot] = useState(undefined)
const url = props.url
useEffect(() => {
async function fetchData() {
// You can await here
const [response, error] = await get(url)
if (error)
log(error)
else {
log(`got response ${response}`)
setScreenshot(response)
}
}
fetchData();
}, [url])
return <div>
<img src={screenShot} className="Screenshot" alt="showing screen capture" />
</div>
}
这篇关于如何从快速后端服务器获取图像并将其显示到 React js 前端?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!