Hy everyone,
I am doing my personal portfolio project. The problem I am facing is that when I set my app get route it works fine, but when i create post route then the get route gives error of post method. All my code is following
routes.js
const express = require(“express”);
const { add } = require(“nodemon/lib/rules”);
const envelopsRoute = express.Router();
const envelops = require(‘…/models/envelops’);
const getEnvelops = require(‘…/models/envelops’);
const addEnvelope = require(“…/models/envelops”);
envelopsRoute.get(‘/’,(req,res ) => {
const envelops = getEnvelops();
res.status(200).send(envelops);
});
envelopsRoute.post(‘/’,(req,res,next) => {
const api = (req.body);
const NewObj = addEnvelope(api);
console.log(NewObj);
res.send(NewObj);
});
envelops js
//
// console.log(ourEnvelop);
module.exports = envelopsRoute;
envelops js
const req = require(“express/lib/request”);
const { type } = require(“express/lib/response”);
title = ‘’;
const envelops = [
{
‘id’: 1,
“title”: “Groceries”,
“budget”: 4000
},
{
'id': 2,
"title": "Gas",
"budget": 2000
},
{
'id': 3,
"title": "Clothing",
"budget": 1000
},
{
'id': 4,
"title": "Health and grooming",
"budget": 2500
},
{
'id': 5,
"title": "GrocerieChildren's items",
"budget": 5000
}
];
const getEnvelops = () => {
return envelops;
};
const addEnvelope = (instance) => {
const {title,budget} = instance;
const newEnvelope = {
id: envelops.length + 1,
title,
budget
};
envelops.push(newEnvelope);
return envelops;
};
// console.log(getEnvelops());
// console.log(addEnvelope());
module.exports = envelops;
module.exports = getEnvelops;
module.exports = addEnvelope;
Now, while executing the get route,
I get the following error
TypeError: Cannot destructure property ‘title’ of ‘instance’ as it is undefined.
at addEnvelope (/home/alihassan/spendingapp/models/envelops.js:49:12)
at /home/alihassan/spendingapp/routes/routes.js:11:26
at Layer.handle [as handle_request] (/home/alihassan/spendingapp/node_modules/express/lib/router/layer.js:95:5)
at next (/home/alihassan/spendingapp/node_modules/express/lib/router/route.js:144:13)
at Route.dispatch (/home/alihassan/spendingapp/node_modules/express/lib/router/route.js:114:3)
at Layer.handle [as handle_request] (/home/alihassan/spendingapp/node_modules/express/lib/router/layer.js:95:5)
at /home/alihassan/spendingapp/node_modules/express/lib/router/index.js:284:15
at Function.process_params (/home/alihassan/spendingapp/node_modules/express/lib/router/index.js:346:12)
at next (/home/alihassan/spendingapp/node_modules/express/lib/router/index.js:280:10)
at Function.handle (/home/alihassan/spendingapp/node_modules/express/lib/router/index.js:175:3)