0

I am a beginner nodejs developer, and for a start I decided to develop a blog project for practice. I am using Nodejs Express and native js on the client. When adding a post, nodejs throws an error in the routes:
(node: 25967) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'title' of undefined at router.post (/routes/post.js:15:25)
Here is my code:


routes/post.js

const express = require('express');
const router = express.Router();
const Post = require('../models/Post');

// http://localhost:5000/api/post (GET)
router.get('/', async (req, res) => {
    const posts = await Post.find({})
    res.status(200).json(posts)
})

// http://localhost:5000/api/post (POST)
router.post('/', async (req, res) => {

    const postData = {
        title: req.body.title,
        text: req.body.text
    }

    const post = new Post(postData)

    await post.save()
    res.status(201).json(post)
})

// http://localhost:5000/api/post/id (DELETE)
router.delete('/:postId', async (req, res) => {
  await  Post.remove({_id: req.params.PostId})
  res.status(200).json({
      message: 'Deleted'
  })
})




module.exports = router

app.js

const express = require('express');
const path = require('path');
const bodyParser = require('body-parser')
const mongoose = require('mongoose');
const postRouter = require('./routes/post');
const keys = require("./keys");

const port = process.env.PORT || 5000;
const clientPath = path.join(__dirname, 'client');

const app = express();
app.use(express.static(clientPath))
app.use('/api/post', postRouter)
app.use(bodyParser.json())


mongoose.connect(keys.mongoURI, { useNewUrlParser: true, 
    useUnifiedTopology: true, useCreateIndex: true })
    .then(() => console.log('MongoDB connected'))
    .catch( err => console.error(err));



app.listen(port, () => {
    console.log(`Server has been started on port ${port}`);
});

(model)Post.js

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const postSchema = new Schema ({
    title: {
        type: String,
        required: true,
    },
    text: {
        type: String,
        required: true
    },
    date : {
        type: Date,
        default: Date.now
    }
})

module.exports = mongoose.model('posts', postSchema)

what could be the problem?

2
  • How are you making the request? What is req.body? Commented Dec 28, 2019 at 22:58
  • I from the client refer to req to the title field, and I want to process in express. I can be wrong, and do something wrong, so ask) Commented Dec 28, 2019 at 23:03

1 Answer 1

2

This is an ordering problem, switch these lines around:

app.use('/api/post', postRouter)
app.use(bodyParser.json())

Express middlewere are run in order, which in your case means your post route will be called before the bodyParser middleware is able to parse the JSON body.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much, I’ve been tormented for half a day, I was looking for an error in the wrong place

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.