3
votes

This is my router

router.post('/', async(req, res) => {

const posts = await loadPostsCollection()

await posts.insertOne({
    text: req.body.text,
    createdAt: new Date()
})
res.status(201).send()
})

This is terminal error

listeining on port 3090 ..... (node:7764) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'text' of undefined at /Users/macbook/Desktop/node-project/server/routes/api/posts.js:19:24 at processTicksAndRejections (internal/process/task_queues.js:94:5) (node:7764) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1) (node:7764) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

1
what does console.log(req.body) give? also it seems for your second err, you should use a trycatch statement.ousecTic

1 Answers

5
votes

This is because your req.body will yield the value undefined. So, when you try to do req.body.text you get an error as you are trying to access the text property on an undefined value.

The reason why you get undefined is because your express app isn't able to parse the request body.

For this, you need to install the body-parser middleware dependency,

npm i body-parser

And then add this middleware to your express app,

const bodyParser = require('body-parser')
app.use(bodyParser.json())

Reference: https://expressjs.com/en/resources/middleware/body-parser.html

Here is an example app,

const express = require('express')
const app = express()
const bodyParser = require('body-parser')
app.use(bodyParser.json())

app.post('/', (req, res) => {
    return res.send(`Hello ${req.body.name}!`)
})

app.listen(3000, () =>
    console.log(`Example app listening at http://localhost:${port}`)
)

Now if you invoke the above example app using curl,

curl -XPOST localhost:3000 -H "Content-Type: application/json" -d '{"name":"Ram"}'

You get back the response "Hello Ram!"