"image.forEach is not a function" 即使是?

"image.forEach is not a function" even though it is?

最近我在使用 EJS 时遇到了这个奇怪的问题。 我正在尝试制作一个简单的自制 Web 图像服务器,一切进展顺利。我可以上传和存储图像,但无法检索它。

我收到“image.forEach”不是函数错误,即使我将其设置为函数。

这是后端:

//Routes
app.get('/', (req, res)=> {
    imageUpload.find({}, (err, data)=> {
        if(err) {
            console.log(err)
            res.status(500)
        } else {
            console.log('> ' + req.ip + " connected to: " + req.url)
            res.render('index.ejs', {
                title: 'Home :: Image Server',
                version: settings.VERSION,
                image: data
            })
        }
    })
})

app.post('/upload', upload.single('img'), (req, res)=> {
    const newImageUpload = new imageUpload({
        img: {
            data: fs.readFileSync(path.join(__dirname + '/uploads/' + req.file.filename)),
            contentType: 'image/png'
        }
    })

    newImageUpload.save((err, data)=> {
        if(err) {
            console.log(err)
            res.status(500)
        } else {
            console.log('> Image succesfully uploaded.')
            res.redirect('/')
        }
    })
})

app.get("/images/:id", (req, res)=> {
    const id = req.params.id

    imageUpload.findById(id, (err, data)=> {
        if(err) {
            console.log(err)
        } else {
            console.log('> ' + req.ip + " connected to: " + req.url)
            res.render('image.ejs', {
                title: 'Home :: Image Server',
                image: data
            })
        }
    })
})

我可以通过“/”路径将图像检索到索引,没有任何问题,但我在“/images/:id”路径上遇到错误。

这里是 'image.ejs' 文件:

<!DOCTYPE html>
<html>
    <head>
        <%= title %> 
    </head>
    <body>
        <% image.forEach((image)=> { %>
            <div>
                <img src="data:image/<%=image.img.contentType%>;base64, <%=image.img.data.toString('base64')%>">
            </div>
        <% }) %> 
    </body>
</html>

我尝试使用 async 和 await,但没有加载路由。 如果有人能帮助我,那将不胜感激!

您的问题是 image.forEach 中的 image 应该是一个 数组 。当您在 / 路由中 .find 时,它会起作用,因为 .finddataarray 发送到它的回调函数。另一方面,在您的 /images/:id 路线中,您的 .findById 函数是 returning 图像对象而不是数组(当您尝试通过唯一标识符查找某些内容时,这是预期的应该只 return 一件事)。如果你想为两个路由保留一个 ejs 文件,这可以通过检查你的 ejs 是否是一个数组(使用 ejs 中的 if 语句和 Array.isArray(image) 检查之类的东西)或只是总是发送一个数组来补救即使只有一个对象。当然,如果您想使用单独的 ejs 文件,您可以随时为 /images/:id 路线做@MohamedOraby 的回答,为 / 路线做你之前的回答。

例如,如果您想始终发送数组并保持 ejs 原样,您可以这样做 /images/:id 路线:

app.get("/images/:id", (req, res)=> {
    const id = req.params.id

    imageUpload.findById(id, (err, data)=> {
        if(err) {
            console.log(err)
        } else {
            console.log('> ' + req.ip + " connected to: " + req.url)
            res.render('image.ejs', {
                title: 'Home :: Image Server',
                image: [data] // this line changed from `image: data` to `image: [data]`
            })
        }
    })
})

尽管我可能不会立即回复,但请随时问我需要澄清的问题。