audioData: ValidatorError: Path `audioData` is required - node.js

When trying to send an audio file to the backend using form data and then on the backend im using multer to parse the data and gridfs to send the data to mongoDB so it can handle a large audio file, im getting an error stating: audioData: ValidatorError: Path audioData is required. also, when i console.log(req.file.buffer) im getting undefined which is telling me my audioFile is not being sent to the backend
here is my App.js file
import React, { useState } from 'react';
const App = () => {
const [selectedFile, setSelectedFile] = useState(null);
const handleFileChange = (event) => {
setSelectedFile(event.target.files[0]);
}
const handleFormSubmit = (event) => {
event.preventDefault();
const formData = new FormData();
formData.append('audioFile', selectedFile);
fetch('http://localhost:4002/audio', {
method: 'POST',
body: formData
})
.then(response => {
if (response.ok) {
return response.json();
} else {
throw new Error('Failed to upload audio file');
}
})
.then(data => {
console.log('File uploaded successfully:', data);
// Do something with the response data
})
.catch(error => {
console.error('Error uploading file:', error);
});
}
return (
<div className="flex h-[100vh] w-[100%] items-center justify-center">
<form onSubmit={handleFormSubmit}>
<input type="file" onChange={handleFileChange} />
<button type="submit" disabled={!selectedFile}>Upload</button>
</form>
</div>
);
};
export default App;
here is my server.js file
const express = require('express');
const mongoose = require('mongoose');
const multer = require('multer');
const { GridFsStorage } = require('multer-gridfs-storage');
const Grid = require('gridfs-stream');
const cors = require('cors');
const app = express();
app.use(express.json());
app.use(cors());
mongoose.connect('mongodb+srv://jordandeeds31:<password>#cluster0.ibeioeb.mongodb.net/?retryWrites=true&w=majority', {
useUnifiedTopology: true,
useNewUrlParser: true,
}).then(() => {
console.log('Connected to MongoDB');
}).catch((err) => {
console.error(err);
});
const conn = mongoose.connection;
let gfs;
conn.once('open', () => {
gfs = Grid(conn.db, mongoose.mongo);
gfs.collection('audioFiles');
});
const storage = new GridFsStorage({
url: 'mongodb+srv://jordandeeds31:Jd400089#cluster0.ibeioeb.mongodb.net/grid?retryWrites=true&w=majority',
file: (req, file) => {
return {
filename: file.originalname,
bucketName: 'audioFiles'
};
}
});
const upload = multer({
storage: storage,
limits: {
fileSize: 90 * 1024 * 1024 // 10MB
},
fileFilter: (req, file, cb) => {
if (file.mimetype.startsWith('audio/')) {
cb(null, true);
} else {
cb(new Error('File type not supported.'));
}
}
});
const audioFileSchema = new mongoose.Schema({
fileUrl: {
type: String,
required: true
},
audioData: {
type: Buffer,
required: true
}
});
const AudioFile = mongoose.model('AudioFile', audioFileSchema);
app.post('/audio', upload.single('audioFile'), async (req, res) => {
try {
if (!req.file) {
return res.status(400).json({ message: 'No file uploaded.' });
}
console.log('req.file.buffer:', req.file.buffer);
const audioFile = new AudioFile({
fileUrl: `http://localhost:4002/audio/${req.file.filename}`,
audioData: req.file.buffer
});
const savedAudioFile = await audioFile.save();
res.json({ fileUrl: savedAudioFile.fileUrl });
} catch (err) {
console.error(err);
if (err instanceof multer.MulterError) {
res.status(400).json({ message: 'File upload error.' });
} else if (err.message === 'File type not supported.') {
res.status(400).json({ message: err.message });
} else {
res.status(500).send('Internal Server Error');
}
}
});
app.get('/audio/:filename', (req, res) => {
const { filename } = req.params;
const readStream = gfs.createReadStream({ filename });
readStream.on('error', (err) => {
console.error(err);
res.status(404).send('File not found.');
});
readStream.pipe(res);
});
app.listen(4002, () => {
console.log('Listening on port 4002');
});

Related

Uploading Images error (NodeJs/Formidable)

I was using formidable#2.0.1 to upload form that contents image, following a tutorial thou. I got the below.
How to debug this error?
Error: The "path" argument must be of type string or an instance of Buffer or URL. Received undefined
Controller.js
const formidable = require("formidable");
const _ = require("lodash");
const fs = require("fs");
const Project = require("../models/projectModel");
exports.create = (req, res) => {
let form = new formidable.IncomingForm();
form.keepExtensions = true;
form.parse(req, (err, fields, files) => {
if (err) {
return res.status(400).json({
error: "Image could not be uploaded",
});
}
let project = new Project(fields);
if (files.image) {
project.image.data = fs.readFileSync(files.image.path);
project.image.contentType = files.image.type;
}
project.save((err, result) => {
if (err) {
return res.status(400).json({
error: errorHandler(error),
});
}
res.json(result);
});
});
};
projectModel.js
const mongoose = require("mongoose");
const { ObjectId } = mongoose.Schema;
const projectSchema = new mongoose.Schema(
{
title: {
type: String,
trim: true,
require: true,
},
category: {
type: ObjectId,
ref: "Category",
required: true,
},
image: {
data: Buffer,
contentType: String,
},
},
{
timestamps: true,
}
);
module.exports = mongoose.model("Project", projectSchema);
In Controller.js I changed files.image.path to files.image.filepath and also changed files.image.type to files.image.mimetype
Controller.js
const formidable = require("formidable");
const _ = require("lodash");
const fs = require("fs");
const Project = require("../models/projectModel");
exports.create = (req, res) => {
let form = new formidable.IncomingForm();
form.keepExtensions = true;
form.parse(req, (err, fields, files) => {
if (err) {
return res.status(400).json({
error: "Image could not be uploaded",
});
}
let project = new Project(fields);
if (files.image) {
project.image.data = fs.readFileSync(files.image.filepath);
project.image.contentType = files.image.mimetype;
}
project.save((err, result) => {
if (err) {
return res.status(400).json({
error: errorHandler(error),
});
}
res.json(result);
});
});
};
use multer npm its works fine
const express = require('express')
const multer = require('multer')
const upload = multer({ dest: 'uploads/' })
const app = express()
app.post('/profile', upload.single('avatar'), function (req, res, next) {
// req.file is the `avatar` file
// req.body will hold the text fields, if there were any
console.log(req.file, req.body)
})

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());

How to Post Data Form to mongoDB with ReactJS using hooks

Hi everyone, I am facing an issue while trying to post data to my mongoDB from the frontend using React Hooks. The problem is that when I send the data instead of getting the all body I am only getting the id as response in my database. I don't know what I am missing in my code, I really need your help and I am open for all advices so I can better understand how to do. Here bellow are my codes:
CustomerPost:
import React, { useState } from "react";
import axios from "axios";
export default function CreateCustomer() {
const [name, setName] = useState("");
const [email, setEmail] = useState("");
const [phone, setPhone] = useState("");
const [passport, setPassport] = useState("");
const [booked, setBooked] = useState(false);
const onChangeName = (e) => {
setName({ name: e.target.value });
};
const onChangeEmail = (e) => {
setEmail({ email: e.target.value });
};
const onChangePhone = (e) => {
setPhone({ phone: e.target.value });
};
const onChangePassport = (e) => {
setPassport({ passport: e.target.value });
};
const onSubmit = (e) => {
e.preventDefault();
const bookingData = {
name: name,
email: email,
phone: phone,
passport: passport,
};
console.log(bookingData);
axios
.post("http://localhost:5000/customers", bookingData)
.then((res) => {
console.log(res.data);
setName(name);
setEmail(email);
setPhone(phone);
setPassport(passport);
})
.catch((error) => {
console.log(error);
});
setBooked(true);
};
return (
<div>
{booked ? (
<p className="bookedMsg">Your room was booked successfully!!!</p>
) : (
<form onSubmit={onSubmit} className="form contact-form">
<div className="input-group-wrap">
<div className="input-group">
<input
className="input"
type="text"
onChange={onChangeName}
placeholder="Name..."
required
/>
<span className="bar"></span>
</div>
<div className="input-group">
<input
className="input"
type="email"
onChange={onChangeEmail}
placeholder="Email..."
required
/>
<span className="bar"></span>
</div>
<div className="input-group">
<input
onChange={onChangePhone}
type="number"
className="input"
placeholder="Phone..."
required
/>
<span className="bar"></span>
</div>
<div className="input-group">
<input
onChange={onChangePassport}
type="number"
className="input"
placeholder="Passport..."
required
/>
<span className="bar"></span>
</div>
</div>
<button type="submit" className="btn form-btn btn-purple">
BOOK NOW
<span className="dots">
<i className="fas fa-ellipsis-h"></i>
</span>
</button>
</form>
)}
</div>
);
}
Customer.Route.js:
const Express = require("express");
var cors = require("cors");
const router = Express.Router();
const Controller = require("./Controller");
const data = require("./controller");
router.post("/", cors(), function (req, res) {
Controller.insertCustomer(req.body)
.then(function (data) {
res.status(data.status).send({ message: data });
})
.catch(function (err) {
res.status(data.status).send({ message: err.message });
});
});
router.get("/", cors(), function (req, res) {
Controller.searchAll()
.then((data) => {
res.status(data.status).send({ data: data.message });
})
.catch((err) => {
res.status(err.status).send({ message: err.message });
});
});
router.get("/:id", cors(), function (req, res) {
Controller.search(req.params.id)
.then((data) => {
res.status(data.status).send({ message: data.message });
})
.catch((err) => {
res.status(err.status).send({ message: err.message });
});
});
router.put("/:id", cors(), function (req, res) {
Controller.updateCustomer(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.delete("/:id", cors(), (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;
dbConfig:
require("dotenv").config();
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const CustomerSchema = new Schema({
name: {
type: String,
require: true,
},
email: {
type: String,
require: false,
},
phone: {
type: Number,
require: true,
},
passport: {
type: Number,
require: true,
},
});
mongoose.connect(
process.env.DATABASE_URL,
{ useNewUrlParser: true, useUnifiedTopology: true },
(err) => {
if (err) {
console.log(err);
}
console.log("Connected to the mongodb");
}
);
module.exports = mongoose.model("Customer", CustomerSchema);
Controller.js:
const mongoose = require("../dbSchema/dbConfig");
const CustomerSchema = mongoose.model("Customer");
const Controller = function () {
this.insertCustomer = function (data) {
return new Promise(function (resolve, reject) {
var Customer = new CustomerSchema({
name: data.name,
email: data.email,
phone: data.phone,
passport: data.passport,
});
Customer.save()
.then(function () {
resolve({ status: 200, message: "Customer inserted Successfully" });
})
.catch(function (err) {
reject({ status: 500, message: "Error " + err });
});
});
};
this.updateCustomer = function (id, data) {
return new Promise((resolve, reject) => {
CustomerSchema.update({ _id: id }, data)
.then(() => {
resolve({ status: 200, message: "Customer updated Successfully" });
})
.catch(function (err) {
reject({ status: 500, message: err });
});
});
};
this.searchAll = function () {
return new Promise(function (resolve, reject) {
CustomerSchema.find()
.exec()
.then(function (data) {
resolve({ status: 200, message: data });
})
.catch(function (err) {
reject({ status: 500, message: err });
});
});
};
this.search = function (id) {
return new Promise(function (resolve, reject) {
CustomerSchema.find({ _id: id })
.exec()
.then(function (Customer) {
resolve({ status: 200, message: Customer });
})
.catch((err) => {
reject({ status: 500, message: err });
});
});
};
this.delete = function (id) {
return new Promise(function (resolve, reject) {
CustomerSchema.remove({ _id: id })
.then(() => {
resolve({ status: 200, message: "Customer Removed" });
})
.catch((err) => {
reject({ status: 500, message: err });
});
});
};
};
module.exports = new Controller();
Route.js:
const Express = require("express");
const Routes = Express.Router();
const CustomerRoute = require("../CustomerController/Customer.Route");
Routes.use("/customers", CustomerRoute);
module.exports = Routes;
It looks like you are sending an empty object from react, can you try adding async and await to your onSubmit function. I'm posting it as an answer to have more space for the code.
const onSubmit = async (e) => {
e.preventDefault();
const bookingData = {
name: name,
email: email,
phone: phone,
passport: passport,
};
console.log(bookingData);
await axios.post("/customers",
bookingData).then((res) => {
console.log(res.data);
setName(name);
setEmail(email);
setPhone(phone);
setPassport(passport);
}).catch((error) => {
console.log(error); });
setBooked(true);
};
Maybe you can modify your handleChange functions, something like this:
const onChangeName = (e) => {
setName(e.target.value)
}
I hope this works for you

Data not saving to mongodb

I'm currently trying upload images to a database by using Mutler and GridFS - which is successful. But I'm also trying to create a caption via the same form, but saving the data into a different schema. My problem is that on the POST route, it's not saving the data to the Posts schema - but no errors are being returned - but as well as that, I'm not being redirected the index page.
model.js schema for caption data
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const PostSchema = new Schema({
caption: {
type: String,
},
fileID: {
type: mongoose.Schema.Types.ObjectId,
ref: 'fs' //created by multer gridfs storage
}
});
const Posts = mongoose.model('Posts', PostSchema);
module.exports = { Posts };
app.js
// Middleware
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }))
app.use(methodOverride("_method"));
app.set("view engine", "ejs");
// Mongo URI
const mongoURI = "mongodb://localhost:27017/grid-fs";
// Mongo connection
const connection = mongoose.createConnection(mongoURI, { useNewUrlParser: true });
// Mongoose Schema
const { Posts } = require('./models/model');
// Init gfs
let gfs;
connection.once("open", () => {
// Init stream
gfs = Grid(connection.db, mongoose.mongo);
gfs.collection("uploads");
})
// Create storage engine
const storage = new GridFsStorage({
url: mongoURI,
file: (req, file) => {
return new Promise((resolve, reject) => {
crypto.randomBytes(16, (err, buf) => {
if (err) {
return reject(err);
}
const filename = buf.toString("hex") + path.extname(file.originalname);
const fileInfo = {
filename: filename,
bucketName: "uploads"
};
resolve(fileInfo);
});
});
}
});
const upload = multer({ storage });
app.get("/", (req, res) => {
gfs.files.find().toArray((err, files) => {
// Check if files exist
if (!files || files.length === 0) {
res.render("index", {files: false})
} else {
files.map(file => {
if(file.contentType === "image/jpeg" || file.contentType === "image/png") {
file.isImage = true;
} else {
file.isImate = false;
}
});
res.render('index', {files: files})
}
});
})
app.post('/upload', upload.single('file'), (req, res) => {
console.log(req.file)
const post = new Posts({
caption: req.body.caption,
fileID: req.file.id
});
console.log(req.body.caption)
console.log(req.file.id)
console.log(post)
post.save().then( result => {
res.redirect('/');
}).catch(err => {
res.status(400).send("Unable to save data");
});
});
I refresh the page the image is pushed to the frontend, but when I check the database the caption content is missing - no schema is there:
try this db.getCollectionNames() and check if your collection is there or not if it doesnot exists
try this
Posts.create({
caption: req.body.caption,
fileID: req.file.id
}, (err, data) => {
if (err) res.status(400).send("Unable to save");
else {
res.redirect("/")
}
})

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