最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Cannot read property 'image' of null - Stack Overflow

programmeradmin1浏览0评论

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.

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.

Share Improve this question edited Jul 11, 2019 at 2:47 Mohamed Essam asked Jul 9, 2019 at 14:45 Mohamed EssamMohamed Essam 852 silver badges10 bronze badges 1
  • 1 req.files is null, so you cannot access the image property of a null object – Dumisani Commented Jul 9, 2019 at 14:50
Add a ment  | 

2 Answers 2

Reset to default 7

Update (June 2022)

Since Ecma262, which came out after this anwser, the safe operator is available in javascript, and supported by most modern browsers. It may be too early to call it widely supported, but it makes the syntax way more friendly (and it should work fine in recent versions of Node).

if (!req?.files?.image) {
 // ...
}

Original Answer (July 2019)

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))

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

发布评论

评论列表(0)

  1. 暂无评论