Gar*_*nde 5 javascript node.js express reactjs axios
我正在尝试从 Express 后端获取图像并将其显示在 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 => {
return(
<img src={res.data} alt="trial" />
)
}
}
Run Code Online (Sandbox Code Playgroud)
这就是我在后端的 server.js 文件中的内容
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}`)
})
Run Code Online (Sandbox Code Playgroud)
我希望图像显示在用户页面中。谢谢。
小智 2
这对我有用:
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>
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
10404 次 |
最近记录: |