Reputation: 49
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())
Upvotes: 2
Views: 10758
Reputation: 4800
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
Upvotes: 1
Reputation: 853
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 }))
Upvotes: 0
Reputation: 101
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 .
Upvotes: 0
Reputation: 11807
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);
Upvotes: 3