error while using deleteOne in app.delete function in Node.js - node.js

** trying to use the app.delete and trying to delete document from mondo db using delete one...it keep throwing errror. how to solve this error ? **
``` require('dotenv').config()
const express = require('express')
const app = express()
const PORT = process.env.PORT || 5001
const connectDB = require('./config/db')
const errorHandler = require('./middleware/error')
const Product =require('./models/product')
const cors = require('cors')
// Connect DB
connectDB()
// Middleware
app.use(cors())
app.use(express.json())
app.use('/auth', require('./routes/authRoutes'))
app.use('/admin', require('./routes/adminRoutes'))
app.use('/customer', require('./routes/customerRoutes'))
app.use('/staff', require('./routes/staffMemberRoutes'))
// error handler - should be *last* piece of middleware
app.use(errorHandler)
app.get('/all-products', (req, res) => {
Product.find({}, (error, posts) => {
if(error) {
res.json({error: 'Unable to fetch products!'})
} else {
res.json(posts)
}
})
})
app.post ('/add-products',(req,res) =>{
console.log("add-products has been fired")
const imageurl = req.body.imageurl
const title = req.body.title
const description = req.body.description
const rate = req.body.rate
const category = req.body.category
const subcategory = req.body.subcategory
let product = new Product({
imageurl: imageurl,
title: title,
description: description,
rate: rate,
category: category,
subcategory: subcategory,
})
product.save((error) => {
if(error) {
res.json({error: 'Unable to save the product!'})
} else {
res.json({success: true, message: 'New product Saved'})
}
})
})
app.delete('/product/:productId', (req, res) => {
const productId = req.params.productId
Product.deleteOne({
_id: productId
}, (error, result) => {
if(error) {
res.json({error: 'Unable to delete product'})
} else {
res.json({success: true, message: 'Product deleted successfully!'})
}
})
})
app.put('/update-product/:productId', (req, res) => {
const productId = req.params.productId
const imageurl = req.body.imageurl
const title = req.body.title
const description = req.body.description
const rate = req.body.rate
const category = req.body.category
const subcategory = req.body.subcategory
const updatedProduct = {
imageurl: imageurl,
title: title,
description: description,
rate: rate,
category: category,
subcategory: subcategory,
}
Product.findByIdAndUpdate(productId, updatedProduct, (error, result) => {
if(error) {
res.json({error: 'Unable to updated the Product'})
} else {
res.json({success: true, message: 'Product updated successfully!'})
}
})
})
const server = app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`)
})
// makes giant server errors concise and simple to read
process.on('unhandledRejection', (err, promise) => {
console.log(`Logged Error: ${err}`)
server.close(() => process.exit(1))
})```

if(error) {
res.json({error: 'Unable to delete product'})
}
In this line, replace res.json with:
res.json({error})
And then comment here the output (error message on the console)

Related

Mongoose suddenly returning empty []

Been following trying to get a mongoose server setup, and it briefly worked, but now it's not for some reason and I honestly have no idea what's going on. No matter what I do, it's returning a blank []?
Collection is "users" all lowercase. Config is in other files. Like I said it has worked before for me briefly and I have no clue why it suddenly stopped.
EDIT - The user object is undefined so it's not even pulling the data from the db for some reason?
server.js
const express = require('express')
const cors = require('cors')
const app = express()
var corsOptions = {
origin: "http://localhost:8080"
}
app.use(cors(corsOptions))
app.use(express.json())
app.use(express.urlencoded({extended:true}))
const db = require('./app/models')
db.mongoose
.connect(db.url, {
useNewUrlParser: true,
useUnifiedTopology: true
})
.then(() => {
console.log("Connected to the database!");
})
.catch(err => {
console.log("Cannot connect to the database!", err);
process.exit();
});
app.get("/", (req, res) => {
res.json({ message: "Welcome to server." });
});
require("./app/routes/user.routes")(app);
const PORT = process.env.PORT || 8080;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}.`);
});
model
module.exports = mongoose => {
var schema = mongoose.Schema(
{
id: Number,
ref: String,
name: String,
achieves: Array,
total: Number
},
{ timestamps: true }
);
schema.method("toJSON", function() {
const { __v, _id, ...object } = this.toObject();
object.id = _id;
return object;
});
const User = mongoose.model("users", schema);
return User;
};
findAll method in controller
exports.findAll = (req, res) => {
const name = req.query.name;
var condition = name ? { name: { $regex: new RegExp(name), $options: "i" } } : {};
User.find(condition)
.then(data => {
res.send(data);
console.log(data);
})
.catch(err => {
res.status(500).send({
message:
err.message || "Some error occurred while retrieving users."
});
});
};
Try this one at query:
{name: {$regex : `.*${name}.*`, $options: "i"}}

Uncaught TypeError: Cannot read properties of undefined (reading 'reviews')

I'm pretty new to react, and I working on a product where I am trying to get the number of individual ratings of a product from the total number of reviews. This is in my front end in my productScreen.js:
const getNumRating = (num) => product.reviews.filter((x) => x.rating === num).length;
The problem that I'm having is that every once in awhile I'm get a Uncaught TypeError: Cannot read properties of undefined (reading 'reviews') error on this line. Reviews comes from reviews: [reviewSchema] in my productModel.js.
I'm unsure as to why I'm getting this. In the return (); portion of my productScreen.js document, I have:{product.reviews.map((review) => (... ))}, which works fine.
Could I not be passing reviews from my backend to my fronted?
This is my ProductRouter.js document:
import express from 'express';
import expressAsyncHandler from 'express-async-handler';
import data from '../data.js';
import Product from '../models/productModel.js';
import { isAdmin, isAuth, isSellerOrAdmin } from '../utils.js';
const productRouter = express.Router();
productRouter.get(
'/seed',
expressAsyncHandler(async (req, res) => {
// await Product.remove({});
const createdProducts = await Product.insertMany(data.products);
res.send({ createdProducts });
})
);
productRouter.get(
'/:id',
expressAsyncHandler(async (req, res) => {
const product = await Product.findById(req.params.id);
if (product) {
res.send(product);
} else {
res.status(404).send({ message: 'Product Not Found' });
}
})
);
productRouter.post(
'/',
isAuth,
isSellerOrAdmin,
expressAsyncHandler(async (req, res) => {
const product = new Product({
name: 'sample name ' + Date.now(),
});
const createdProduct = await product.save();
res.send({ message: 'Product Created', product: createdProduct });
})
);
productRouter.put(
'/:id',
isAuth,
isSellerOrAdmin,
expressAsyncHandler(async (req, res) => {
const productId = req.params.id;
const product = await Product.findById(productId);
if (product) {
product.name = req.body.name;
const updatedProduct = await product.save();
res.send({ message: 'Product Updated', product: updatedProduct });
} else {
res.status(404).send({ message: 'Product Not Found' });
}
})
);
productRouter.delete(
'/:id',
isAuth,
isAdmin,
expressAsyncHandler(async (req, res) => {
const product = await Product.findById(req.params.id);
if (product) {
const deleteProduct = await product.remove();
res.send({ message: 'Product Deleted', product: deleteProduct });
} else {
res.status(404).send({ message: 'Product Not Found' });
}
})
);
productRouter.post(
'/:id/reviews',
isAuth,
expressAsyncHandler(async (req, res) => {
const productId = req.params.id;
const product = await Product.findById(productId);
if (product) {
if (product.reviews.find((x) => x.name === req.user.name)) {
return res
.status(400)
.send({ message: 'You already submitted a review' });
}
const review = {
name: req.user.name,
rating: Number(req.body.rating),
comment_title: req.body.comment_title,
comment: req.body.comment,
age: req.body.age,
customerImages: req.body.customerImages,
};
product.reviews.push(review);
product.numReviews = product.reviews.length;
product.rating =
product.reviews.reduce((a, c) => a = a +c.rating, 0) /
product.reviews.length;
const updatedProduct = await product.save();
res.status(201).send({
message: 'Review Created',
review: updatedProduct.reviews[updatedProduct.reviews.length - 1],
});
} else {
res.status(404).send({ message: 'Product Not Found' });
}
})
);
export default productRouter;
I also tried to add numRating5 to my productModel.js, and
product.numRating5 = product.reviews.filter((x) => x.rating === 5).length;
after product.rating in productRouter.post(...) in productRouter.js, but that just gave me an Uncaught TypeError: Cannot read properties of undefined (reading 'numRating5') error in the frontend.
I would really appreciate any help or advice on how to fix this. Thank you!
The problem is probably related to the fact that the product has not been loaded from the API when you are trying to access it.
Adding a null-check should prevent the error:
const getNumRating = (num) => {
if (!product) return 0;
return product.reviews.filter((x) => x.rating === num).length;
}

node js : test rest API

i'm new learner in backend node js ... in my code below i created an API for questions and it contains get,post,delete and edit
i wanted to test it using the extension rest client in VS code but when i type Get http://localhost:3000/api in route.rest file to test it,it stucks on waiting
is there a way to know if my API works good and can somebody please help me if i have mistake below?
thanks in advance
//server.js
// #ts-nocheck
const express = require('express');
const morgan = require('morgan');
const mongoose = require('mongoose');
const dotenv = require('dotenv');
const jwt = require('jsonwebtoken');
const questionRoutes = require('./routes/subscribers');
const cors = require('cors');
const http = require('http');
// Has to be move but later
const multer = require("multer");
const Question = require('./models/subscriber');
// express app
const app = express();
// Explicitly accessing server
const server = http.createServer(app);
// corsfffffffff
app.use(cors());
dotenv.config();
const dbURI = process.env.MONGO_URL || "mongodb://localhost:27017/YourDB";
mongoose.connect(dbURI, { useNewUrlParser: true, useUnifiedTopology: true })
.then(result => server.listen(process.env.PORT || 3000) )
.catch(err => console.log(err));
// register view engine
app.set('view engine', 'ejs');
app.use(express.json);
// middleware & static files
app.use(express.static('public'));
app.use(express.urlencoded({ extended: true }));
app.use(morgan('dev'));
app.use((req, res, next) => {
res.locals.path = req.path;
next();
});
// routes
// question routes
app.use('/questions' , questionRoutes );
// 404 page
app.use((req, res) => {
res.status(404).render('404', { title: '404' });
});
//questionRoute.js
const express = require('express');
const questionController = require('../controllers/questionCon');
const questionApiController = require('../controllers/questionApiController');
const router = express.Router();
// API Routing
router.get('/api/', questionApiController.get_questions);
router.post('/api/add', questionApiController.create_question);
router.get('/api/:id', questionApiController.get_question);
router.delete('/api/delete/:id', questionApiController.delete_question);
router.put('/api/update/:id', questionApiController.update_question);
// EJS Routing for GUI
router.get('/create', questionController.question_create_get);
router.get('/', questionController.question_index);
router.post('/', questionController.question_create_post);
router.get('/:id', questionController.question_details);
router.delete('/:id', questionController.question_delete);
module.exports = router;
//question.js
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const questionSchema = new Schema({
questionTitle: {
type: String,
required: true,
},
description: {
type: String,
},
price: {
type: Number,
},
});
const Question = mongoose.model('Question', questionSchema);
module.exports = Question;
//questionAPIcontroller
const Question = require('../models/subscriber');
const validators = require('../validators');
let questionApiController = {
// Get a single question
get_question : async (req , res) => {
const id = req.params.id;
try {
const question = await Question.findById(id,(err, question) => {
if (err) return res.status(400).json({response : err});
res.send("hello")
res.status(200).json({response : question})
console.log("hello")
})
} catch (err) {
res.status(400).json(err);
}
},
// Get all the questions
get_questions: async (req , res) => {
try {
const questions = await Question.find((err, questions) => {
if (err) return res.status(400).json({response : err});
res.status(200).json({response : questions})
})
} catch (err) {
res.status(400).json(err);
}
},
// Create a question
create_question : async (req , res) => {
const {error} = validators.postQuestionValidation(req.body);
if(error) return res.status(400).json({ "response" : error.details[0].message})
try {
const question = await new Question(req.body);
question.save((err, question) => {
if (err) return res.status(400).json({response : err});
res.status(200).json({response : " Question created Successfully"})
});
} catch (err) {
res.status(400).json(err);
}
},
// Delete question
delete_question : async (req , res) => {
const id = req.params.id;
var questionExist = false;
var userId ;
const question = await Question.findById(id).then(result => {
questionExist = true;
userId = result.owner;
}).catch(err => {
questionExist = false;
res.status(400).json({response : err });
});
if(questionExist){
try {
Question.findByIdAndRemove(id ,(err, question) => {
// As always, handle any potential errors:
if (err) return res.json({response : err});
// We'll create a simple object to send back with a message and the id of the document that was removed
// You can really do this however you want, though.
const response = {
message: "Question successfully deleted",
id: question._id
};
return res.status(200).json({response : response });
});
} catch (err) {
res.status(400).json(err);
}
}
else {
return res.status(400).send( { "response" : "A question with that id was not find."});
}
},
// Update question
update_question : async (req , res) => {
const id = req.params.id;
Question.findByIdAndUpdate(id,req.body,
function(err, result) {
if (err) {
res.status(400).json({response : err});
} else {
res.status(200).json({response : "Question Updated"});
console.log(result);
}
})
},
// Get question's questions
}
module.exports = questionApiController
//questionController
const Question = require('../models/subscriber');
const question_index = (req, res) => {
Question.find().sort({ createdAt: -1 })
.then(result => {
res.render('index', { questions: result, title: 'All questions' });
})
.catch(err => {
console.log(err);
});
}
const question_details = (req, res) => {
const id = req.params.id;
Question.findById(id)
.then(result => {
res.render('details', { question: result, title: 'Question Details' });
})
.catch(err => {
console.log(err);
res.render('404', { title: 'Question not found' });
});
}
const question_create_get = (req, res) => {
res.render('create', { title: 'Create a new question' });
}
const question_create_post = (req, res) => {
const question = new Question(req.body);
question.save()
.then(result => {
res.redirect('/questions');
})
.catch(err => {
console.log(err);
});
}
const question_delete = (req, res) => {
const id = req.params.id;
Question.findByIdAndDelete(id)
.then(result => {
res.json({ redirect: '/questions' });
})
.catch(err => {
console.log(err);
});
}
module.exports = {
question_index,
question_details,
question_create_get,
question_create_post,
question_delete
}
change code
app.use(express.json);
to
app.use(express.json());

Sequelize and socket.io to retrieve chart.js data in real time (Angular frontend)

I'm new to PostgreSQL and I'm wondering if it's possible to get real-time data for my front-end chart using socket.io. I've been trying to follow some examples but I can't get it to work with my sequelize setup. I tried establishing a connection in my server.js file but when it runs it skips the code and goes right into my sequelize query. I posted how I tried connecting at the bottom.
My server.js File
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const app = express();
app.use(cors({ origin: '*' }));
global.__basedir = __dirname;
// parse requests of content-type - application/json
app.use(bodyParser.json());
// parse requests of content-type - application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: true }));
const dotenv = require('dotenv');
dotenv.config();
const db = require('./app/models');
db.sequelize.sync().then(() => {
console.log('Re-sync db.');
});
// simple route
app.get('/', (req, res) => {
res.json({ message: 'Hello from server.' });
});
require('./app/routes/bitcoin.routes')(app);
// set port, listen for requests
const PORT = process.env.PORT || 8080;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}.`);
});
bitcoin.model.js
module.exports = (sequelize, Sequelize) => {
const Bitcoin = sequelize.define(
'bitcoin',
{
date: {
type: Sequelize.STRING
},
txvolume_usd: {
type: Sequelize.DOUBLE
},
adjustedtxvolume_usd: {
type: Sequelize.DOUBLE
},
txcount: {
type: Sequelize.INTEGER
},
marketcap_usd: {
type: Sequelize.DOUBLE
},
price_usd: {
type: Sequelize.DOUBLE
},
exchangevolume_usd: {
type: Sequelize.DOUBLE
},
generatedcoins: {
type: Sequelize.DOUBLE
},
fees: {
type: Sequelize.DOUBLE
},
activeaddresses: {
type: Sequelize.INTEGER
},
averagedifficulty: {
type: Sequelize.DOUBLE
},
paymentcount: {
type: Sequelize.DOUBLE
},
mediantxvalue_usd: {
type: Sequelize.DOUBLE
},
medianfee: {
type: Sequelize.DOUBLE
},
blocksize: {
type: Sequelize.INTEGER
},
blockcount: {
type: Sequelize.INTEGER
}
},
{ timestamps: false }
);
Bitcoin.removeAttribute('id');
return Bitcoin;
};
models.index.js
const dbConfig = require('../config/db.config.js');
const Sequelize = require('sequelize');
const sequelize = new Sequelize(dbConfig.DB, dbConfig.USER, dbConfig.PASSWORD, {
host: dbConfig.HOST,
port: dbConfig.port,
dialect: dbConfig.dialect,
dialectOptions: {
ssl: {
require: true,
rejectUnauthorized: false
}
},
operatorsAliases: 0,
pool: {
max: dbConfig.pool.max,
min: dbConfig.pool.min,
acquire: dbConfig.pool.acquire,
idle: dbConfig.pool.idle
}
});
const db = {};
db.Sequelize = Sequelize;
db.sequelize = sequelize;
db.bitcoin = require('./bitcoin.model.js')(sequelize, Sequelize);
module.exports = db;
Bitcoin Controller
const db = require('../models');
const Bitcoin = db.bitcoin;
const Op = db.Sequelize.Op;
// Create and Save a new Bitcoin
exports.create = (req, res) => {
// Validate request
if (!req.body.date) {
res.status(400).send({
message: 'Content can not be empty!'
});
return;
}
// Create a Bitcoin
const bitcoin = {
date: req.body.date,
txvolume_usd: req.body.txvolume_usd,
adjustedtxvolume_usd: req.body.adjustedtxvolume_usd,
txcount: req.body.txcount,
marketcap_usd: req.body.marketcap_usd,
price_usd: req.body.price_usd,
exchangevolume_usd: req.body.exchangevolume_usd,
generatedcoins: req.body.generatedcoins,
fees: req.body.fees,
activeaddresses: req.body.activeaddresses,
averagedifficulty: req.body.averagedifficulty,
paymentcount: req.body.paymentcount,
mediantxvalue_usd: req.body.mediantxvalue_usd,
medianFmedianfeeee: req.body.medianfee,
blocksize: req.body.blocksize,
blockcount: req.body.blockcount
};
// Save Bitcoin in the database
Bitcoin.create(bitcoin)
.then((data) => {
res.send(data);
})
.catch((err) => {
res.status(500).send({
message: err.message || 'Some error occurred while creating the Bitcoin entry.'
});
});
};
exports.findAll = (req, res) => {
const date = req.query.date;
var condition = date ? { date: { [Op.iLike]: `%${date}%` } } : null;
Bitcoin.findAll({ where: condition })
.then((data) => {
res.send(data);
})
.catch((err) => {
res.status(500).send({
message: err.message || 'Some error occurred while retrieving bitcoin entries.'
});
});
};
// Find a single Bitcoin entry with an id
exports.findOne = (req, res) => {
const id = req.params.id;
Bitcoin.findByPk(id)
.then((data) => {
res.send(data);
})
.catch((err) => {
res.status(500).send({
message: 'Error retrieving bitcoin entry with id=' + id
});
});
};
// Update a Bitcoin entry by the id in the request
exports.update = (req, res) => {
const id = req.params.id;
Bitcoin.update(req.body, {
where: { id: id }
})
.then((num) => {
if (num == 2) {
res.send({
message: 'Bitcoin entry was updated successfully.'
});
} else {
res.send({
message: `Cannot update Bitcoin entry with id=${id}. Maybe it was not found or the body is empty!`
});
}
})
.catch((err) => {
res.status(500).send({
message: 'Error updating Bitcoin entry with id=' + id
});
});
};
// Delete a Bitcoin entry with the specified id in the request
exports.delete = (req, res) => {
const id = req.params.id;
Bitcoin.destroy({
where: { id: id }
})
.then((num) => {
if (num == 1) {
res.send({
message: 'Bitcoin entry was deleted successfully!'
});
} else {
res.send({
message: `Cannot delete Bitcoin entry with id=${id}. Maybe it was not found!`
});
}
})
.catch((err) => {
res.status(500).send({
message: 'Could not delete Bitcoin entry with id=' + id
});
});
};
// Delete all Bitcoin entries from the database.
exports.deleteAll = (req, res) => {
Bitcoin.destroy({
where: {},
truncate: false
})
.then((nums) => {
res.send({ message: `${nums} Bitcoin entries were deleted successfully!` });
})
.catch((err) => {
res.status(500).send({
message: err.message || 'Some error occurred while removing all bitcoin entries.'
});
});
};
Changes I Tried To server.js
const express = require('express');
const app = express();
const server = require('http').createServer(app);
const io = require('socket.io')(server);
const bodyParser = require('body-parser');
const cors = require('cors');
let timerId = null;
let sockets = new Set();
app.use(express.static(__dirname + '/dist'));
io.on('connection', (socket) => {
sockets.add(socket);
console.log(`Socket ${socket.id} added`);
if (!timerId) {
startTimer();
}
socket.on('clientdata', (data) => {
console.log(data);
});
socket.on('disconnect', () => {
console.log(`Deleting socket: ${socket.id}`);
sockets.delete(socket);
console.log(`Remaining sockets: ${sockets.size}`);
});
});

How to create a Mongo database to Node.js?

I have created the backend operations using Node.js / MongoDB and created services for them, but when I run the server it indicates that I've connected successfully, but I can't see a database in Robo 3T.
Here is what I coded:
DBConfig.js
var mongoose = require ('mongoose');
var Schema = mongoose.Schema;
var UserSchema = new Schema({
name : {
type : String,
require : true
},
address : {
type : String,
require : true
}
});
mongoose.model("User", UserSchema);
module.exports = mongoose;
mongoose.connect('mongodb://127.0.0.1:27017/TestDB4', function(err){
if(err)
{
console.log(err);
process.exit(-1);
}
console.log("Connected to the db")
});
I can't see an error. Why isn't the DB created?
check your User.Controller.js as this below,
var mongoose = require('../DBSchema/SchemaMapper');
var UserSchema = mongoose.model('User');
var UserController = function(){
this.insert = (data) => {
return new Promise((resolve, reject) => {
var user = new UserSchema({
userName: data.userName,
password: data.password
});
user.save().then(() => {
resolve({status: 200, message: "Added new user"});
}).catch(err => {
reject({status: 500, message: "Error:- "+err});
})
})
}
this.update = (id, data) => {
return new Promise((resolve, reject) => {
UserSchema.update({_id: id}, data).then(() => {
resolve({status: 200, message: "update user"});
}).catch(err => {
reject({status: 500, message: "Error:- " + err});
})
})
}
this.searchAll = () => {
return new Promise((resolve, reject) => {
UserSchema.find().exec().then((data) => {
resolve({status: 200, data: data});
}).catch(err => {
reject({status: 500, message: "Error:- " + err});
})
})
}
this.search = (id) => {
return new Promise((resolve, reject) => {
UserSchema.find({_id:id}).exec().then(user => {
resolve({status: 200, data: user});
}).catch(err => {
reject({status: 500, message: "Error:- " + err});
})
})
}
this.delete = (id) => {
return new Promise((resolve, reject) => {
UserSchema.remove({_id:id}).then(() => {
resolve({status: 200, message: "remove user"});
}).catch(err => {
reject({status: 500, message:"Error:- " + err});
})
})
}
}
module.exports = new UserController();
And User.Route.js as below,
var express = require('express');
var router = express.Router();
var Controller = require('./User.Controller');
router.post('/', (req, res) => {
Controller.insert(req.body).then(data => {
res.status(data.status).send({message: data.message});
}).catch(err => {
res.status(err.status).send({message: err.message});
})
});
router.put('/:id', (req, res) => {
Controller.update(req.params.id, req.body).then(data => {
res.status(data.status).send({message: data.message});
}).catch(err => {
res.status(err.status).send({message: err.message});
})
});
router.get('/', (req, res) => {
Controller.searchAll().then(data => {
res.status(data.status).send({data: data.data});
}).catch(err => {
res.status(err.status).send({message: err.message});
});
});
router.get('/:id', (req, res) => {
Controller.search(req.params.id).then(data => {
res.status(data.status).send({data: data.data});
}).catch(err => {
res.status(err.status).send({message: err.message});
});
});
router.delete('/:id', (req, res) => {
Controller.delete(req.params.id).then(data => {
res.status(data.status).send({message: data.message});
}).catch(err => {
res.status(err.status).send({message: err.message});
})
})
module.exports = router;
check your app.js as follows
const Express = require("express");
const BodyParser = require("body-parser");
const Routes = require("./Routes");
const Cors = require("cors");
const app = Express();
app.use(Cors());
app.use(BodyParser.urlencoded({ extended: false }));
app.use(BodyParser.json());
app.use('/', Routes);
app.listen(8083, 'localhost', (err) => {
if(err) {
console.log(err);
process.exit(-1);
}
console.log("Server listen port 8083");
});
and Routes.js as follows,
var Express = require("express");
var Routes = Express.Router();
var UserRoute = require('./src/User/User.Route');
var CommentRoute = require('./src/Comment/Comment.Route');
Routes.use('/user/', UserRoute);
Routes.use('/comment/', CommentRoute);
module.exports = Routes;

Resources