1
votes

Cannot read property 'image' of null at module.exports

module.exports = (req, res, next) => {
if (!req.files.image) {
    return res.redirect('/posts/new')
}

next()}

index.js :

const express = require('express')

const app = new express()

const path = require('path')

const expressEdge = require('express-edge')

const mongoose = require('mongoose')

const bodyParser = require('body-parser')

const Post = require('./database/models/Post')

const fileUpload = require('express-fileupload')



mongoose.connect('mongodb://localhost/node-js-blog', { useNewUrlParser:       true })

app.use(express.static('public'))

app.use(fileUpload())

app.use(expressEdge)

app.set('views', `${__dirname}/views`)

app.use(bodyParser.json())
app.use(bodyParser.urlencoded({extended : true}))

const storePost = require('./middleware/storePosts')
app.use('/posts/store', storePost)

app.get('/',async (req, res)=>{
const posts = await Post.find({})
console.log(posts)
res.render('index',{
    posts
})
})

app.get('/about', (req,res)=>{
res.render('about')
})

app.get('/post/:id', async (req,res)=>{
const post = await Post.findById(req.params.id)
res.render('post',{
    post
})
})

app.get('/contact', (req,res)=>{
res.render('contact')
})

app.get('/posts/new', (req,res)=>{
res.render('create')
})

app.post("/posts/store", (req, res) => {
const {image} = req.files

image.mv(path.resolve(__dirname, 'public/posts', image.name), (error) => {
    Post.create({
        ...req.body,
        image: `/posts/${image.name}`
    }, (error, post) => {
        res.redirect('/');
    });
})
});

app.listen(3000, ()=>{
console.log('start server')
})

create.edge:

<div class="form-group mt-5">
                    <input type="file" name="image" class="form-control-file">
                  </div>

when i use middleware.js to headlining not inserting image it give me this error when user not upload image file and return TypeError: Cannot read property 'image' of null at module.exports (/home/mohamedessam/Desktop/NodeJs/middleware/storePosts.js:2:20) at Layer.handle [as handle_request] (/home/mohamedessam/Desktop/NodeJs/node_modules/express/lib/router/layer.js:95:5) at trim_prefix (/home/mohamedessam/Desktop/NodeJs/node_modules/express/lib/router/index.js:317:13) at /home/mohamedessam/Desktop/NodeJs/node_modules/express/lib/router/index.js:284:7 at Function.process_params (/home/mohamedessam/Desktop/NodeJs/node_modules/express/lib/router/index.js:335:12) at next (/home/mohamedessam/Desktop/NodeJs/node_modules/express/lib/router/index.js:275:10) at urlencodedParser (/home/mohamedessam/Desktop/NodeJs/node_modules/body-parser/lib/types/urlencoded.js:100:7) at Layer.handle [as handle_request] (/home/mohamedessam/Desktop/NodeJs/node_modules/express/lib/router/layer.js:95:5) at trim_prefix (/home/mohamedessam/Desktop/NodeJs/node_modules/express/lib/router/index.js:317:13) at /home/mohamedessam/Desktop/NodeJs/node_modules/express/lib/router/index.js:284:7 at Function.process_params (/home/mohamedessam/Desktop/NodeJs/node_modules/express/lib/router/index.js:335:12) at next (/home/mohamedessam/Desktop/NodeJs/node_modules/express/lib/router/index.js:275:10) at jsonParser (/home/mohamedessam/Desktop/NodeJs/node_modules/body-parser/lib/types/json.js:119:7) at Layer.handle [as handle_request] (/home/mohamedessam/Desktop/NodeJs/node_modules/express/lib/router/layer.js:95:5) at trim_prefix (/home/mohamedessam/Desktop/NodeJs/node_modules/express/lib/router/index.js:317:13) at /home/mohamedessam/Desktop/NodeJs/node_modules/express/lib/router/index.js:284:7.

2
req.files is null, so you cannot access the image property of a null object - Dumisani

2 Answers

7
votes

Thats because you always directly check for the sub-property image, but at some point you didn’t set the req.files in which it is nested. Since req.files doesn’t exist, it returns a null type, which javascript cannot parse.

You first need to check if all parent key exist individually, in javascript, to test the existence of a nested key in an object. The following should fix the issue :

if (!(req.files && req.files.image))
-1
votes

as the javascript is case sensitive, you should give the exact name as used in the form for the image