2

I'm still trying to understand routing in node.js, Other routes like route.get(all) and single id are working perfectly, but "router.post" is giving an error in postman such as "TypeError: Cannot read property email of undefined";

For the index.js

const express = require('express');
const redflags_table = require('../db/redflags_table');
const router = express.Router();


router.put('/api/v1/redflag/:id', (req, res) => {
  const id = parseInt(req.params.id, 10);
  let recordFound;
  let itemIndex;
  redflags_table.map((record, index) => {
    if (record.id === id) {
      recordFound = record;
      itemIndex = index;
    }
  });

  if (!recordFound) {
    return res.status(404).send({
      success: 'false',
      message: 'todo not found',
    });
  }

  if (!req.body.email) {
    return res.status(400).send({
      success: 'false',
      message: 'title is required',
    });
  }
  const updatedRedflag = {
    id: recordFound.id,
    email: req.body.email || recordFound.email
  };

  redflags_table.splice(itemIndex, 1, updatedRedflag);

  return res.status(201).send({
    success: 'true',
    message: 'todo added successfully',
    updatedRedflag,
  });
});

The app.js:

const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const router = require('./routes/index.js');

app.use(router);



app.use(bodyParser.urlencoded({ extended: true }));
router.use(bodyParser.json())
sheryl
  • 49
  • 1
  • 2
  • 10

4 Answers4

3

Rearrage the order of your middleware.

const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const router = require('./routes/index.js');


app.use(bodyParser.urlencoded({ extended: true }));
router.use(bodyParser.json())
app.use(router);
james emanon
  • 11,185
  • 11
  • 56
  • 97
1

UPDATE 2021

Now body-parser is deprecated, you can use express:

import express from 'express'

const app = express()

app.use(express.json({limit: '20mb'}))
app.use(express.urlencoded({ extended: false, limit: '20mb' }))

export default app
Álvaro Agüero
  • 4,494
  • 1
  • 42
  • 39
  • Thanks' this work's for me, i have 1 question! why limit: 20 ?? can you explain me this or give me a good url news! – AllisLove Aug 05 '21 at 15:23
0

If you are using Mongoose then it can be solved by fixing options .like this mongoose.set('useFindAndModify', false);

Hopefully your problem will be sorted .

0

You can fix this with these simple steps.

install body parser for content-type - application/x-www-form-urlencoded

1) npm i --save body-parser

2)go into your root file in your case it is index.js add these lines of code before routes.

//require body-parser

const bodyParser = require('body-parser')

app.use(bodyParser.urlencoded({ extended: true }))
Saad Abbasi
  • 745
  • 11
  • 25