Cannot read properties of undefined (reading 'push') - javascript

I'm trying to create a Note taker app, but when click on save any information, is coming a TypeError: Cannot read properties of undefined (reading 'push')
Below the code for Note.js
const path = require('path');
const fs = require('fs');
const uniqid = require('uniqid');
let noteList = [];
function findById(id, noteList) {
return noteList.filter(note => note.id === id)[0];
}
function addNewNote(body, noteList) {
let newNote = body;
newNote.id = uniqid();
noteList.push(newNote);
fs.writeFileSync(
path.join(__dirname, '../db/db.json'),
JSON.stringify({db: noteList}, null, 2)
);
return newNote;
}
function removeNote (id, noteList) {
const removeThisNote = findById(id, noteList);
for (let i = 0; i<noteList.length; i++){
if (noteList[i].id === removeThisNote.id) {
noteList.splice(i, 1);
fs.writeFileSync(
path.join(__dirname, '../db/db.json'),
JSON.stringify({db: noteList}, null, 2)
);
}
};
}
module.exports = {
findById,
addNewNote,
removeNote
};
api index.js
const router = require('express').Router();
const {db} = require('../db/db.json');
const { addNewNote, removeNote} = require('../lib/note.js');
router.get('/notes', (req, res) => {
let results = db;
res.json(results);
})
router.post('/notes', (req, res) => {
const newNote = addNewNote(req.body, db);
res.json(newNote);
})
router.delete('/notes/:id', (req, res) => {
removeNote(req.params.id, db);
res.json(req.body);
})
module.exports = router;
Server.js
const express = require(`express`);
const apiRoutes = require('./routes/apiRoutes.js');
const path = require('path');
// const htmlRoutes = require('./routes/htmlRoutes.js');
const PORT = process.env.PORT || 3001;
const app = express();
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use('/api', apiRoutes)
// app.use('/', htmlRoutes)
app.use(express.static(`public`));
//Routes
app.get(`/notes`, (req, res) => {
console.log(`Note page requested`);
res.sendFile(path.join(__dirname, `public/notes.html`));
});
app.get(`/`, (req, res) => {
console.log(`Home page requested`);
res.sendFile(path.join(__dirname, `public/index.html`));
});
app.listen(PORT, () =>
console.log(`App listening at http://localhost:${PORT}`)
);
Can anyone help with this ?
I want to deploy this using Heroku but when testing save any info, error comes up.

push() is an Array method. Therefore, the error shows that some variable is not array but undefined.
The addNewNote function contains a variable called noteList and the error says it is not an array.
So, the argument you pass to this function is not an array.
I suggest you check the db variable you import from db.json and see if this is an array because this is the variable you pass as an argument in addNewNote.

Related

TypeError: Prismic.getApi is not a function

i'm really struggling while trying to build a website from scratch without a framework. And now i'm integrating Prismic in through node.js, but as I'm following all the passages i'm getting stuck by this error shown in the log of the terminal: TypeError: Prismic.getApi is not a function.
As a consequence of this i can see the local website but the about link doesn't load. How can i fix that?
This is the main code related to the package.json
require('dotenv').config()
console.log(process.env.PRISMIC_ENDPOINT, process.env.PRISMIC_CLIENT_ID)
const express = require('express')
const app = express()
const path = require('path')
const port = 3000
const Prismic = require('#prismicio/client')
const PrismicDOM = require('prismic-dom')
const initApi = req => {
return Prismic.getApi(process.env.PRISMIC_ENDPOINT, {
accessToken: process.env.PRISMIC_ACCESS_TOKEN,
req
})
}
const handlelinkResolver = doc => {
// Define the url depending on the document type
// if (doc.type === 'page'){
// return '/page/' + doc.uid;
// } else if (doc.type === 'blog_post'){
// return '/blog/' + doc.uid;
// }
// Default to homepage
return '/'
}
app.use((req, res, next) => {
res.locals.ctx = {
endpoint: process.env.PRISMIC_ENDPOINT,
linkResolver: handlelinkResolver
}
res.locals.PrismicDOM = PrismicDOM
next()
})
app.set('views', path.join(__dirname, 'views'))
app.set('view engine', 'pug')
app.get('/', async (req, res) => {
res.render('pages/home')
})
app.get('/about', async (req, res) => {
initApi(req).then((api) => {
api.query(
Prismic.Predicates.at('document.type', 'about')
).then(response => {
console.log(response)
res.render('pages/about')
})
})
})
app.get('/personaggi', (req, res) => {
res.render('pages/personaggi')
})
app.get('/detail/:uid', (req, res) => {
res.render('pages/detail')
})
app.listen(port, () => {
console.log(`Example app listening on port ${port}`)
})
You can use :
const Prismic = require('prismic-javascript')
// NB : This package has been deprecated but it's still working.
Instead of :
const Prismic = require('#prismicio/client')
OR you can use the actual setup guide of Prismic at https://prismic.io/docs/technologies/express-install
As user bmz1 mentionned, getApi() is no longer used in version 6+. Downgrade #prismicio/client.
In your package.json dependencies, replace by :
"#prismicio/client": "5.1.0"
Don't forget to run npm i to reset your dependencies

nodejs : nodemon app crashed - waiting for file changes before starting

I was actually following a nodejs course on Udemy and suddenly down the course, the code started breaking and giving some errors. I then tried copying the instructor's code, but still, the problem was the same.
I also followed this answer on StackOverflow itself but the problem remains the same.
I am attaching all the js files below and also the error message from the terminal below:
Error message from the terminal
This is what the file structure looks like
Now the js files:
app.js file:
const express = require('express');
const bodyParser = require('body-parser');
const path = require('path');
const adminRoutes = require('./routes/admin');
const shopRoutes = require('./routes/shop');
const errorController = require('./controllers/error');
const app = express();
app.set('view engine', 'ejs');
app.set('views', 'views');
app.use(bodyParser.urlencoded({extended:false}));
app.use(express.static(path.join(__dirname, 'public')));
app.use('/admin', adminRoutes);
app.use(shopRoutes);
app.use(errorController.get404Page);
app.listen(3000);
controllers/error.js file:
exports.get404 = (req, res, next) => {
res.status(404).render('404', { pageTitle: 'Page Not Found' });
};
controllers/products.js file
const Product = require('../models/product');
exports.getAddProduct = (req, res, next) => {
res.render('add-product', {
pageTitle: 'Add Product',
path: '/admin/add-product',
formsCSS: true,
productCSS: true,
activeAddProduct: true
});
};
exports.postAddProduct = (req, res, next) => {
const product = new Product(req.body.title);
product.save();
res.redirect('/');
};
exports.getProducts = (req, res, next) => {
Product.fetchAll(products => {
res.render('shop', {
prods: products,
pageTitle: 'Shop',
path: '/',
hasProducts: products.length > 0,
activeShop: true,
productCSS: true
});
});
};
models/product.js file :
const fs = require('fs');
const path = require('path');
const p = path.join(
path.dirname(process.main.filename),
'data',
'products.json'
);
const getProductsFromFile = cb => {
fs.readFile(p, (err, fileContent) => {
if (err) {
cb([]);
} else {
cb(JSON.parse(fileContent));
}
});
};
module.exports = class Product {
constructor(t) {
this.title = t;
}
save() {
getProductsFromFile(products => {
products.push(this);
fs.writeFile(p, JSON.stringify(products), err => {
console.log(err);
});
});
}
static fetchAll(cb) {
getProductsFromFile(cb);
}
};
routes/admin.js file:
const path = require('path');
const express = require('express');
const productsController = require('../controllers/products');
const router = express.Router();
// /admin/add-product => GET
router.get('/add-product', productsController.getAddProduct);
// /admin/add-product => POST
router.post('/add-product', productsController.postAddProduct);
module.exports = router;
routes/shop.js file:
const path = require('path');
const express = require('express');
const productsController = require('../controllers/products');
const router = express.Router();
router.get('/', productsController.getProducts);
module.exports = router;
util/path.js file:
const path = require('path');
module.exports = path.dirname(process.main.filename);
I am new to backend development, nodejs to be specific. Please help me find my mistake.
In many file you have used process.main.filename, but there is no property named process.name for node.js process, so process.main is undefined. As a result reading the property process.main.filename gives the error.
So, to solve your problem:
Replace every process.main.filename with
process.mainModule.filename OR require.main.filename
(there is difference in both, but it will not matter in your app.)
and see if it works. I guess this is a mistake on your part while writing the code.
Tip: Always try to understand the error using terminal output. That way You can solve most of the problems.

Cannot POST to CosmosDB using Angular

I am trying to post to my cosmosDB using Angular. I can GET just fine, but POST returns with a 404 error in Postman. I am new to routes and APIs so I am a little lost on what is causing the issue.
Here is my index.js
const bodyParser = require('body-parser');
const path = require('path');
const routes = require('./routes');
const root = './';
const port = process.env.PORT || '3000';
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static(path.join(root, 'dist/checkin')));
app.use('/api', routes);
app.get('*', (req, res) => {
res.sendFile('dist/checkin/index.html', {root});
});
app.listen(port, () => console.log(`API running on localhost:${port}`));
My routes.js
const contactService = require('./contact.service');
const router = express.Router();
router.get('/contacts', (req, res) => {
contactService.getContacts(req, res);
});
router.post('/contact/', (req, res) => {
contactService.postContact(req, res);
});
module.exports=router;
My contact.service.js which contains all of my operations (Just GET and POST right now)
const ReadPreference = require('mongodb').ReadPreference;
require('./mongo').connect();
function getContacts(req, res) {
const docquery = Contact.find({}).read(ReadPreference.NEAREST);
docquery
.exec()
.then(contacts => {
res.status(200).json(contacts);
})
.catch(error => {
res.status(500).send(error);
return;
});
}
function postContact(req, res) {
const originalContact = { uid: req.body.uid, name: req.body.name, description: req.body.description };
const contact = new Contact(originalContact);
contact.save(error => {
if (checkServerError(res, error)) return;
res.status(201).json(contact);
console.log('Contact created successfully!');
});
}
function checkServerError(res, error) {
if (error) {
res.status(500).send(error);
return error;
}
}
module.exports = {
getContacts,
postContact
};
Input is obtained through an HTML forum which is picked up and sent through
return this.http.post<Contact>(`${api}/contact/`, contact);
}

how to fix "can't read property push of undefined" error in Nodejs?

I have coded a simple app to learn Nodejs but when i run "nodemon index.js" in cmd i have this error
TypeError: Cannot read property 'push' of undefined
app crashed - waiting for file changes before starting...
i have follow all instruction in the udemy course for learn nodejs
and i faced this problem when i separated the file into two files index.js and genres.js
genres.js
const express = require('express');
const router = express.Router;
//simple data
const genres = [{
id: 1,
name: 'course1'
},
{
id: 2,
name: 'course2'
},
{
id: 3,
name: 'course3'
}
];
//////////////////////////////////////////////////////////////////////
/////////////////////////////////// Get //////////////////////////////
//////////////////////////////////////////////////////////////////////
router.get('/', (req, res) => {
res.send(genres);
});
router.get('/:id', (req, res) => {
const genre = genres.find(c => c.id ===
parseInt(req.params.id)); //req.params.id return string
if (!genre)
return res.status(404).send('The course is not found...');
res.send(genre);
res.send(req.params.id);
});
router.get('/:year/:month', (req, res) => {
res.send(req.params);
});
router.post('/', (req, res) => {
const {
error
} = validategenre(req.body);
if (error)
return res.status(400).send(error.details[0].message);
const genre = {
id: genres.length + 1,
name: req.body.name
}
genres.push(genre);
res.send(genre);
});
router.put('/:id', (req, res) => {
const genre = genres.find(c => c.id === parseInt(req.params.id));
if (!genre)
return res.status(404).send('The course does not exist !!! ');
const result = validategenre(req.body);
if (result.error)
return res.status(400).send(result.error.details[0].message);
genre.name = req.body.name;
res.send(genre);
});
function validategenre(genre) {
const schema = {
name: Joi.string().min(3).required()
};
return Joi.validate(genre, schema);
}
module.exports = router;
index.js
const Joi = require('joi');
const genres = require('./routes/genres');
const express = require('express');
const app = express();
app.use(express.json());
app.use('/api/genres', genres);
const port = process.env.PORT || 3000;
app.listen(port, () => console.log(`Listining on port ${port}...`));
In genres.js, you should import
const router = express.Router();
instead of
const router = express.Router;
Also, the error you mention could be from any push in your code (without any more info), please specify the stacktrace next time :)
Use const router = express.Router() instead of const router = express.Router.
It can be wrong variable name :)
I made a mistake due to intelligence in my quick sample -
Typically signature of a ReST call is
router.get("/something", (req: any, res: any, next: any) => {
response.write("test");
response.end();
});
Here if you will notice I was using response where as i was suppose to use res
Moreover ensure you have registered your routes using
app.use(router);

Route.delete() requires a callback function but got a [object Object]

I have node-express app where I have bunch of Routes for login, logout and signup and one Route for checking authorised Route which can be accessed only through providing authToken. I moved the Routes to separate Route file and I got the above error.
This is my Users Routes File:
const express = require('express');
const authenticate = require('./../middleware/authenticate');
const router = express.Router();
const {User} = require('./../models/user');
router.post('/',(req, res) => {
var body = _.pick(req.body,['email','password']);
var user = new User(body);
user.save().then(() => {
return user.generateAuthToken()
}).then((token) => {
res.header('x-auth', token).send(user);
}).catch((e) => {
res.status(400).send(e);
});
});
router.post('/login',(req, res) => {
var body = _.pick(req.body, ['email', 'password']);
User.findByCredentials(body.email, body.password).then((user) => {
return user.generateAuthToken().then((token) => {
res.header('x-auth', token).send(user);
});
}).catch((e) => {
res.status(400).send(e);
});
});
router.delete('/logout',authenticate, (req, res) => {
req.user.removeToken(req.token).then(() => {
res.status(200).send();
},(e) => {
res.status(400).send(e);
}) ;
});
router.get('/me',authenticate, (req,res) => {
res.send(req.user);
});
module.exports = router;
Following is my main server.js file:
const express = require('express');
const _ = require('lodash');
var app = express();
const usersRoutes = require('./routes/users');
app.use(express.json());
app.use('/users', usersRoutes);
var {mongoose} = require('./db/mongoose');
var {User} = require('./models/user');
var {authenticate} = require('./middleware/authenticate');
const port = process.env.PORT || 3000 ;
app.listen(port, () => console.log(`Listening on ${port}...`))
I have a model/Schema(mongoose) file for User so If You feel you need that I am ready to edit my question. Thanks.
The problem is that router.delete is expecting a function on the middleware parameter (like you did in your server.js file with app.use(express.json())) so it can be used like a callback which gets called whenever a request reach your route.
Try changing authenticate to authenticate().
It seems like in your users routes file you are importing the entire module who contains the authenticate function, so when try to access it like a function you'll get an error. You need to import it like you did in your server.js file.
Change the line const authenticate = require('./../middleware/authenticate'); for const {authenticate} = require('./../middleware/authenticate');.

Categories