Using two different Schemas in NodeJS Express - node.js

I have a nodeJs application which is working fine with one schema from MSSQL, but i have a requirement where i need to use another schema and do some api calls.
first API is working fine and giving out result.
But when I tried with another get api named "/stockOrderDetails" it is just giving empty data like this:
Can anyone please let me know how to use different schemas in a single JS file for nodeJS
{
"code": 200,
"status": "OK",
"message": "Data Operation Success",
"data": {
"orderDetail": [
]
}
}
Here is my actual code:
const express = require("express");
var sql = require("mssql");
const { json, urlencoded } = require("body-parser");
const multer = require("multer");
var config = {
user: "jsudjac",
password: "********",
server: "********",
database: "JSULLC_Test",
};
var dataSource = {
user: "jsudjac",
password: "*****",
server: "*********",
database: "Stock_Test",
};
const dbconn1 = sql.connect(config, (err) => {
if (!err) {
console.log("Connected to the database");
} else {
console.log("Problem in connecting to database");
console.log(err);
console.log("testing");
}
});
const dbconn2 = sql.connect(dataSource, (err) => {
if (!err) {
console.log("connected");
} else {
console.log(err);
}
});
const storage = multer.diskStorage({
destination: "./uploads",
filename: function (req, file, cb) {
cb(null, Date.now() + "-" + file.originalname);
},
});
const app = express();
app.use(function (req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
next();
});
const upload = multer({
storage: storage,
dest: "./uploads/",
}).single("file");
app.use(json());
app.use(urlencoded({ extended: true }));
app.get("/jsuOrderDetails/:jsuOrder", (req, res) => {
const request = new sql.Request(dbconn1);
request.input("jsuOrder", sql.VarChar, req.params.jsuOrder);
request.execute("mobile_getOrderDetails", (err, result) => {
if (!err) {
var out = {
code: 200,
status: "OK",
message: "Data Operation Success",
data: {
orderDetail: result.recordsets[0],
},
};
} else {
var out = {
status: 404,
data: {},
};
}
res.send(out);
});
});
app.get("/stockOrderDetails/:jsuOrder", (req, res) => {
const request = new sql.Request(dbconn2);
console.log("hithithit");
request.input("jsuOrder", sql.VarChar, req.params.jsuOrder);
console.log(req.params.jsuOrder);
request.execute("mobile_getOrderDetails", (err, result) => {
if (!err) {
var out = {
code: 200,
status: "OK",
message: "Data Operation Success",
data: {
orderDetail: result.recordsets[0],
},
};
} else {
var out = {
status: 404,
data: {},
};
}
res.send(out);
});
});
app.get("/validate", (req, res) => {
let query = "select * from ma_smallpipe_coating_details";
console.log("hithit");
dbconn2.query(query, (err, rows) => {
if (!err) {
console.log(rows.recordsets[0]);
}
});
});```

Related

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

I am getting 404 error and 204 error when consuming backend (node,vuejs)?

When signing in with postman everything works fine. But when i am doing an axios request i get 404 error and directly after 204 error. When i render my vue.js page i get "cannot get api/auth/signin. Also I get a message somewhere that says user not found.
What i have tried:
Frontend: I tried with adding headers to my axios request. I console logged the data and it seems perfectly fine.
Backend: Changed deprecated body parsers.
Frontend Code:
Auth store
import axios from "axios";
const state = {
token: "",
users: [],
};
const getters = {};
const actions = {
async signIn(_, payload) {
const response = await axios.post(
"http://localhost:3000/api/auth/signin",
{ payload },
{
headers: {
"Content-Type": "application/json",
},
}
);
console.log(response.data);
console.log(response.headers);
console.log(response.status);
},
};
const mutations = {};
export default {
state,
getters,
actions,
mutations,
};
This is my backend:
Controller
//signin
exports.signin = (req, res) => {
User.findOne({
username: req.body.username,
})
.populate("roles", "-__v")
.exec((err, user) => {
if (err) {
res.status(500).send({ message: err });
return;
}
if (!user) {
return res.status(404).send({ message: "User Not found." });
}
var passwordIsValid = bcrypt.compareSync(
req.body.password,
user.password
);
if (!passwordIsValid) {
return res.status(401).send({
accessToken: null,
message: "Invalid Password!",
});
}
var token = jwt.sign({ id: user.id }, config.secret, {
expiresIn: 86400, // 24 hours
});
var authorities = [];
for (let i = 0; i < user.roles.length; i++) {
authorities.push("ROLE_" + user.roles[i].name.toUpperCase());
}
res.status(200).send({
id: user._id,
username: user.username,
email: user.email,
roles: authorities,
accessToken: token,
});
});
};
Route
module.exports = function (app) {
app.use(function (req, res, next) {
res.header(
"Access-Control-Allow-Headers",
"x-access-token, Origin, Content-Type, Accept"
);
next();
});
app.post(
"/api/auth/signup",
[
verifySignUp.checkDuplicateUsernameOrEmail,
verifySignUp.checkRolesExisted,
],
controller.signup
);
app.post("/api/auth/signin", controller.signin);
And my server
const express = require("express");
const bodyParser = require("body-parser");
const cors = require("cors");
const jwt = require("jsonwebtoken");
const mongoose = require("mongoose");
const Quote = require("./models/Quote");
const quoteRoute = require("./routes/quoteRoute");
const quoteController = require("../Maxico/controllers/quoteController");
const config = require("./config/config");
const verifySignup = require("./middlewares/verifySignUp");
const Role = require("./models/Role");
const app = express();
//Import routes
//const authRoute = require("./routes/auth");
var corsOptions = {
origin: "http://localhost:8080/?#/",
};
app.use(cors(corsOptions));
app.use(express.urlencoded({ extended: true }));
app.use(express.json()); //
const db = require("./models/Quote");
mongoose
.connect(
"url",
{
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: false,
}
)
.then(() => {
console.log("Connected to the database!");
})
.catch((err) => {
console.log("Cannot connect to the database!", err);
process.exit();
});
app.use(express.json());
app.get("/", (req, res) => {
res.send("Welcome to homepage");
});
app.use("/quote", quoteRoute);
require("./routes/authRoute")(app);
//require("./routes/userRoute")(app);
// initial roles
Role.estimatedDocumentCount((err, count) => {
if (!err && count === 0) {
new Role({
name: "user",
}).save((err) => {
if (err) {
console.log("error", err);
}
console.log("added 'user' to roles collection");
});
new Role({
name: "moderator",
}).save((err) => {
if (err) {
console.log("error", err);
}
console.log("added 'moderator' to roles collection");
});
new Role({
name: "admin",
}).save((err) => {
if (err) {
console.log("error", err);
}
console.log("added 'admin' to roles collection");
});
new Role({
name: "superadmin",
}).save((err) => {
if (err) {
console.log("error", err);
}
console.log("added 'superadmin' to roles collection");
});
}
});
// set port, listen for requests
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}.`);
});
In my network tab the request pay load got sent like this:
{payload: {username: "jon", password: "password"}}
payload: {username: "jon", password: "password"}
But my postman only accepts this:
{username: "jon", password: "password"}
So in my action i sent like this:
const actions = {
async signIn(_, payload) {
console.log(payload);
const response = await axios.post(
"http://localhost:3000/api/auth/signin",
payload,
{
headers: {
"Content-Type": "application/json",
},
}
);
console.log(payload);
console.log(response.data);
console.log(response.headers);
console.log(response.status);
},
};

rest full service in express web application

I have to implement a express web application to use rest services with mongodb.
my DBConfig.js file is like below which include my db schema,
var Mongoose = require("mongoose");
const Schema = Mongoose.Schema;
const UserSchema = new Schema({
name : {
type: String,
require: true
},
address : {
type: String,
require: false
},
password: {
type: String,
require: true
}
});
Mongoose.model('User', UserSchema);
Mongoose.connect("mongodb://localhost:27017/demo", function (err) {
if (err) {
console.log(err);
process.exit(-1);
}
console.log("Connected");
});
module.exports = Mongoose;
all the relevant methods are implement in my Controller.js file
var Mongoose = require("../DBSchema/DBConfig");
var UserSchema = Mongoose.model('User');
var Controller = function() {
this.insertUser = function (data) {
return new Promise(function(resolve, reject) {
var User = new UserSchema({
name: data.name,
address: data.address,
password: data.password
});
User.save().then(function () {
resolve({status: 200, message: "User inserted successfully"})
}).catch(function (err) {
reject({status: 500, message: "Error:- " + err})
});
});
}
this.getAll = function () {
return new Promise(function (resolve, reject) {
UserSchema.find().exec().then(function (data) {
resolve({status: 200, Userdata: data})
}).catch(function (err) {
resolve({status: 500, message : "No data available"})
})
})
}
this.getuser = function (id) {
return new Promise(function (resolve, reject) {
UserSchema.find({_id: id}).exec().then(function (data) {
resolve({status: 200, userSearched: data});
}).catch(function (err) {
reject({status: 404, message: "User NOT FOUND"});
})
})
}
this.updateUser = function (id, data) {
return new Promise(function (resolve, reject) {
UserSchema.update({_id: id}, data).then(function (data) {
resolve({status: 200, message: "User updated successfully"})
}).catch(function (err) {
reject({status: 500, message: "Error:- " + err})
})
})
}
this.remove = function (id) {
return new Promise(function (resolve, reject) {
UserSchema.remove({_id: id}).then(function () {
resolve({status: 200, message: "Successfully deleted"})
}).catch(function (err) {
resolve({status: 500, message: "Error : "+err})
})
})
}
}
module.exports = new Controller();
now I have to call my rest services,I want to know how can I use these methods which are in my controller to access data.
I'm using postman to view my data.
the output should be
{
"data": [
{
"_id": "5cf724a58c9b061ba062a28c",
"name": "name1",
"address": "adress1",
"password": "password1",
"__v": 0
}
]
}
All you need is you have to define the routes in your URL to access relevant method, example I create a file called User.Routes.js under a folder called UserController which you can add your Controller.js file also to arrange in an order to get a clear idea. and also assume you add your DBConfig.js file under folder called DBSchema, which made you to do good code practise.
var Express = require('express');
var router = Express.Router();
var Controller = require('./Controller')
router.get('/',function (req,res) {
Controller.getAll().then(function (data) {
res.status(data.status).send({data:data.Userdata})
});
});
router.get('/:id',function (req,res) {
Controller.getuser(req.params.id).then(function (data) {
res.status(data.status).send({data:data.userSearched});
});
});
router.post('/',function(req,res){
Controller.insertUser(req.body).then(function (data) {
res.status(data.status).send({message: data.message});
}).catch(function (err) {
res.status(err.status).send({message: err.message});
});
});
router.put('/:id',function (req,res) {
Controller.updateUser(req.params.id,req.body).then(function (data) {
res.status(data.status).send({message: data.message});
});
});
router.delete('/:id', function (req,res) {
Controller.remove(req.params.id).then(function (data) {
res.status(data.status).send({message: data.message});
});
});
module.exports = router;
and now you need to use methods in your User.Routes.js via postman. for that you need to give url name to be accessed. example, I create Routes.js file
const Express = require("express");
var Routes = Express.Router();
var UserRoute = require('./UserController/User.Route');
Routes.use('/user/', UserRoute);
module.exports = Routes;
like this if you want to view data from your schema you have to add the url like -"http://localhost:8083/user"
and your app.js file want to require the created Routes file for that you can do like,
const Express = require("express");
const app = Express();
const BodyParser = require("body-parser");
const Routes = require("./Routes");
app.use(BodyParser.json());
app.use("/", Routes);
app.listen(8083, "localhost", function(err) {
if (err) {
console.log(err);
process.exit(-1);
}
console.log("Server listening on port 8083");
});
Now using postman you can add user,update and delete particular user by giving user id in your URL like - "http://localhost:8083/user/5cf724a58c9b061ba062a28c"

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;

res.render in node with controller response to jade

this is a part of my model
router.get('/subscription', function (req, res, next) {
var membership = require('../controllers/membership.js');
var jData = membership.getAll(req, res);
res.render('subscription', { title: 'Subscription', data : jData });
});
this is a part of my controller.js
var db = require('../db.js');
module.exports = {
//home: function (req, res, next) {
// res.send('home page');
//},
insert: function (req, res) {
var body = req.body; //_.pick(req.body, 'description', 'completed');
db.membership.create(body).then(function (membership) {
res.json(membership.toJSON());
}, function (e) {
res.status(500).json(e);
});
},
updateById: function (req, res, next) {
//var Id = parseInt(req.params.id, 10);
var body = req.body;
db.membership.update(body, { where: { id: parseInt(_.propertyOf(body)('id'), 10) } }).then(function (membership) {
if (!!membership) {
res.json(membership.toJSON());
} else {
res.status(404).send();
}
}, function (e) {
res.status(500).json(e);
});
},
deleteById: function (req, res, next) {
//var Id = parseInt(req.params.id, 10);
var body = req.body;
db.membership.destroy({ where: { id: parseInt(_.propertyOf(body)('id'), 10) } }).then(function (membership) {
if (!!membership) {
console.log('The Row with the Id : ' + _.propertyOf(body)('id') + ' deleted successfully!');
} else {
res.status(404).send();
}
}, function (e) {
res.status(500).json(e);
});
},
deleteAll: function (req, res, next) {
db.membership.truncate().then(function () {
console.log('All rows deleted successfully!');
}, function (e) {
res.status(500).json(e);
});
},
getById: function (req, res) {
var Id = parseInt(req.params.id, 10);
db.membership.findById(Id).then(function (membership) {
if (!!membership) {
console.log('\n\nMEMBERSHIP : ' + JSON.stringify(membership.toJSON()));
res.json(membership.toJSON());
//return membership.toJSON();
} else {
res.status(404).send();
}
}, function (e) {
res.status(500).send();
});
},
getAll: function (req, res) {
var where = {};
db.membership.findAll({
where: where
}).then(function (membership) {
res.json(membership.toJSON());
}, function (e) {
res.status(500).send();
});
}
};
i am trying to get aal data in my model data comes perfectly so no issue in controller
but res.render function data could not be passed to jade.
according to me res.render function call before jdata variable filled.
any solution about it tell me.
thanks in advance
You can't send the response two times, if you send the res in the controller you can't send it again in the model, you should use a callback:
Controller:
getAll: function(cb) {
var where = {};
db.membership.findAll({
where: where
}).then(function(membership) {
cb({
data: membership.toJSON()
});
}, function(e) {
cb({
error: e
});
});
}
Model:
router.get('/subscription', function (req, res, next) {
var membership = require('../controllers/membership.js');
var jData = membership.getAll(function (cb) {
if (cb.error) res.status(400).send();
res.render('subscription', { title: 'Subscription', data : cb.data });
});
});

Resources