ibrahima92 / fullstack-typescript-mern-todo

Full-stack TypeScript App with React, Nodejs and MongoDB
154 stars 82 forks source link

Still having body parser issue #16

Open FadedWill opened 3 years ago

FadedWill commented 3 years ago

I checked other people's comments in another issue, but it doesn't seem like working anymore. The req.body is still undefined.

[1] (node:23772) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'name' of undefined [1] at C:\dev\fullstack-typescript-mern-todo\server\dist\js\controllers\todos\index.js:31:24 [1] at Generator.next () [1] at C:\dev\fullstack-typescript-mern-todo\server\dist\js\controllers\todos\index.js:8:71 [1] at new Promise () [1] at __awaiter (C:\dev\fullstack-typescript-mern-todo\server\dist\js\controllers\todos\index.js:4:12) [1] at addTodo (C:\dev\fullstack-typescript-mern-todo\server\dist\js\controllers\todos\index.js:27:31) [1] at Layer.handle [as handle_request] (C:\dev\fullstack-typescript-mern-todo\server\node_modules\express\lib\router\layer.js:95:5) [1] at next (C:\dev\fullstack-typescript-mern-todo\server\node_modules\express\lib\router\route.js:137:13) [1] at Route.dispatch (C:\dev\fullstack-typescript-mern-todo\server\node_modules\express\lib\router\route.js:112:3)

Azarchaniel commented 3 years ago

@FadedWill I fixed this by putting app.use(express.json()) into server/src/app.ts. BUT! Make sure it's first of app.use! My app.ts now looks like this:

import express, { Express } from 'express'
import mongoose from 'mongoose'
import cors from 'cors'
import todoRoutes from './routes'

const app: Express = express()

const PORT: string | number = process.env.PORT || 4000

app.use(express.json())
app.use(cors())
app.use(todoRoutes)

const uri: string = `mongodb+srv://${process.env.MONGO_USER}:${process.env.MONGO_PASSWORD}@cluster0.og6qo.mongodb.net/${process.env.MONGO_DB}?retryWrites=true&w=majority`
const options = { useNewUrlParser: true, useUnifiedTopology: true }
mongoose.set('useFindAndModify', false)

mongoose
    .connect(uri, options)
    .then(() =>
        app.listen(PORT, () =>
            console.log(`Server running on http://localhost:${PORT}`)
        )
    )
    .catch((error) => {
        throw error
    })
Devtr0n commented 3 years ago

@Azarchaniel Thank you so much, you just saved me a big headache!! I too was faced with the null req.body and was typing up an issue for it....

just to explain further, what I was seeing after getting everything to compile correctly and finally run....this was happening (when I attempt to add a "todo"):

image

adding app.use(express.json()) to app.ts solved it for sure, cheers!!

Nikhil-github-webrtc commented 2 years ago

This helped a lot.