程序问答   发布时间:2022-06-02  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了“无法读取未定义的属性‘contentType’”大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

如何解决“无法读取未定义的属性‘contentType’”?

开发过程中遇到“无法读取未定义的属性‘contentType’”的问题如何解决?下面主要结合日常开发的经验,给出你关于“无法读取未定义的属性‘contentType’”的解决方法建议,希望对你解决“无法读取未定义的属性‘contentType’”有所启发或帮助;

过去一周我一直在开发一款小型图片共享社交媒体应用。一切都很顺利,直到我不得不从数据库中检索图像。

我不断收到“无法读取未定义的属性‘ContentType’”错误,

  1. 数据分配给“ContentType”,并且,
  2. 由于此时数据库中没有图像,它甚至不应该查找 ContentType。 (查看示例代码)

如果有人能帮助指导正确的方向,那就太好了! ?

仅供参:数据库中没有图像。上传工作正常,只是检索导致问题 - 是的,我知道,您无法检索不存在的图像,但它甚至不应该在第一个中查找 ContentType地点。

代码如下:

索引路由(这是发生错误的路由)

// @ROUTE: Home Route
// @DESCRIPTION: Renders the homepage
server.get('/',(req,res)=> {
    filesDB.find({},(err,data)=> {
        if(err) {
            throw err
        }

        if(!data) {
            console.log("No Images")
        } else if(data) {
            res.render('Home.eJs',{
                pagetitle: "Home :: imgHub",cursession: req.session,images: [data]
            })
        }
    })
})

Home.eJs

<!DOCTYPE HTML>
    <HTML lang="en">
    <head>
        <Meta charset="UTF-8">
        <Meta http-equiv="X-UA-Compatible" content="IE=edge">
        <Meta name="vIEwport" content="wIDth=device-wIDth,initial-scale=1.0">
        <title><%= pagetitle %></title>
    </head>
    <body>
        <header>
            <%- include('./Partials/header.eJs') %> 
        </header>
        <main>
            <% if(images.length > 0) { %>
                <% images.forEach((images)=> { %>
                    <div>
                        <img src="data:images/<%= images.img.ContentType %>;base64,<%= images.img.data.toString('base64') %>">
                    </div>
                <% }) %>
            <% } else { %>
                <h2>No Images Found...</h2>
            <% } %>
        </main>
    </body> 
</HTML>

上传帖子

// @POST: Upload Post
// @DESCRIPTION: Saves the image's data onto the database.
server.post('/API/upload',fileUpload.single('fileinput'),res)=> {
    const newfile = new filesDB({
        img: {
            data: fs.readfileSync(path.join(__dirname + '/Uploads/' + req.file.fileName)),ContentType: 'image/png'
        },uploader: req.session.username
    })

    newfile.save((err,data)=> {
        if(err) {
            throw err
        } else {
            console.log(`> ${req.session.usernamE} has uploaded: ${req.file.filename}`)
            res.redirect('/')
        }
    })
})

上传文件架构和模型

const mongoose = require('mongoose')

const filescheR_135_11845@a = new mongoose.scheR_135_11845@a({
    img: {
        data: Buffer,ContentType: String
    },uploader: String
},{timestamps: truE})

const fileModel = new mongoose.model('file',filescheR_135_11845@a)
module.exports = fileModel

错误

TypeError: D:\Github RepositorIEs\RepositorIEs\imgHub\imgHub\vIEws\Home.eJs:17
    15|                 <% images.forEach((images)=> { %>

    16|                     <div>

 >> 17|                         <img src="data:images/<%= images.img.ContentType %>;base64,<%= images.img.data.toString('base64') %>">

    18|                     </div>

    19|                 <% }) %>

    20|             <% } else { %>


CAnnot read property 'ContentType' of undefined
    at eval (eval at compile (D:\Github RepositorIEs\RepositorIEs\imgHub\imgHub\node_modules\eJs\lib\eJs.Js:662:12),<anonymous>:24:37)
    at Array.forEach (<anonymous>)
    at eval (eval at compile (D:\Github RepositorIEs\RepositorIEs\imgHub\imgHub\node_modules\eJs\lib\eJs.Js:662:12),<anonymous>:21:15)
    at Home (D:\Github RepositorIEs\RepositorIEs\imgHub\imgHub\node_modules\eJs\lib\eJs.Js:692:17)
    at tryHandleCache (D:\Github RepositorIEs\RepositorIEs\imgHub\imgHub\node_modules\eJs\lib\eJs.Js:272:36)
    at VIEw.exports.renderfile [as ENGIne] (D:\Github RepositorIEs\RepositorIEs\imgHub\imgHub\node_modules\eJs\lib\eJs.Js:489:10)
    at VIEw.render (D:\Github RepositorIEs\RepositorIEs\imgHub\imgHub\node_modules\express\lib\vIEw.Js:135:8)
    at tryRender (D:\Github RepositorIEs\RepositorIEs\imgHub\imgHub\node_modules\express\lib\application.Js:640:10)
    at Function.render (D:\Github RepositorIEs\RepositorIEs\imgHub\imgHub\node_modules\express\lib\application.Js:592:3)
    at ServerResponse.render (D:\Github RepositorIEs\RepositorIEs\imgHub\imgHub\node_modules\express\lib\response.Js:1012:7)
    at D:\Github RepositorIEs\RepositorIEs\imgHub\imgHub\server.Js:94:17
    at D:\Github RepositorIEs\RepositorIEs\imgHub\imgHub\node_modules\mongoose\lib\model.Js:5068:18
    at processticksAndRejections (node:internal/process/task_queues:78:11)

图像模型 https://i.imgur.com/efHHRc9_d.webp?maxwidth=760&fidelity=grand

解决方法

根据 Mongoose API,您的 filesDB.find 返回对象的数组,而不仅仅是单个对象。因此您的 images: [data] 不正确,您需要使用:

        if(!data.length) {
            console.log("No Images")
        } else {
            res.render('Home.ejs',{
                pagetitle: "Home :: ImgHub",cursession: req.session,images: data,})
        }
,

在 mongo 集合上调用 find 时,如果找不到数据,它将返回一个空数组。然后,您的支票:

if(!data) {
    console.log("No Images")
} else if(data) {
    res.render('Home.ejs',{
        pagetitle: "Home :: ImgHub",images: [data]
    })
}

将在 else 情况下进行,因为 [] 是真实的。并且在调用 render 时,images 属性将为 [[]],因此长度为 1 并通过 images.length > 0 检查。

将您的代码更改为以下内容,您应该会看到您想要的

if(data.length === 0) {
    console.log("No Images")
} else {
    res.render('Home.ejs',images: data
    })
}

大佬总结

以上是大佬教程为你收集整理的“无法读取未定义的属性‘contentType’”全部内容,希望文章能够帮你解决“无法读取未定义的属性‘contentType’”所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。