英文:
Want to show the image that i get from db as by its name
问题
Your provided code is in English, but you've requested a translation. Here's the translated code:
问题是我上传的图像被设置在数据库中,并保存在VS Code的uploads文件夹中,但我不知道如何在前端显示它们。我尝试了一些方法,但需要进一步了解该过程。
<script>
axios
.get("http://localhost:8000/hotels")
.then((response) => {
console.log(response.data)
for (let i = 0; i < response.data.length; i++) {
document.getElementById('data').innerHTML += `<tr class="odd">
<td class="dtr-control sorting_1" tabindex="0">${response.data[i].id}</td>
<td><img src='${response.data[i].image}'></td>
<td>${response.data[i].name}</td>
<td>${response.data[i].description}</td>
<td>${response.data[i].price}</td>
<td>${response.data[i].address}</td>`;
}
})
.catch((error) => {
console.log(error);
});
</script>
在这里,您可以看到,当我上传数据时,图像存储在uploads文件夹中,我们只需找到一种方法在前端显示图像即可。
英文:
SO my problem is images that i upload are set in the database and saves in vs code in uploads folder but i dont know how to display them on front end i have tried something but furthur needs to know the procedure
<script>
axios
.get(
"http://localhost:8000/hotels")
.then((response) => {
console.log(response.data)
for (let i = 0; i < response.data.length; i++) {
document.getElementById('data').innerHTML+=`<tr class="odd">
<td class="dtr-control sorting_1" tabindex="0">${response.data[i].id}</td>
<td><img src='${response.data[i].image}'></td>
<td>${response.data[i].name}</td>
<td>${response.data[i].description}</td>
<td>${response.data[i].price}</td>
<td >${response.data[i].address}</td>`
}
})
.catch((error) => {
console.log(error);
});
</script>
答案1
得分: 1
您的/uploads文件夹不像其他路由一样被托管。您需要托管它以解决URL。
编辑:解释
在您的app.js/index.js(您已初始化app()的位置)中编写以下代码:
const path = require('path')
app.use('/uploads',
express.static(path.join(__dirname,
'uploads')))
我也认为这个问题类似于如何使用Node.js提供图像的问题。
英文:
Your /uploads folder is not hosted like other routes. you need to host it in order to resolve the URL.
Here is how you can using express.
EDIT: Explanation
In your app.js/index.js(where you have initialized app())
write the code below
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
const path = require('path')
app.use('/uploads',
express.static(path.join(__dirname,
'uploads')))
<!-- end snippet -->
Also i believe the question is similar to How to serve an image using nodejs
答案2
得分: -3
你可以使用以下代码替代:
<td><img src='${new URL("uploads/"+response.data[i].image, window.location.origin).toString()}'></td>
英文:
You can use instead of
<td><img src='${response.data[i].image}'></td>
this line
<td><img src='${new URL("uploads/"+response.data[i].image, window.location.origin).toString()}'></td>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论