API Connection through node in React Form - node.js

const express = require('express');
const mysql = require('mysql');
const app = express();
const bodyParser = require('body-parser');
var cors = require('cors');
app.use(cors());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
function getConnection() {
return mysql.createConnection({
host: 'localhost',
user: 'root',
database: 'pms_tool'
})
}
//DEL REQUEST
app.delete('/users/:kpiId', (req, res) => {
console.log('Fetching user with kpiId: ' + req.params.kpiId);
const connection = getConnection();
const Id = req.params.kpiId;
const queryString = 'DELETE FROM kpi_master WHERE kpiId = ?';
connection.query(queryString, [Id], (err, rows, fields) => {
if (err) {
console.log('Failed to query for users: ' + err);
res.sendStatus(500);
return;
}
res.end('Record has been deleted!!!');
});
});
//update kpi api
app.put("/kpi_update/:kpiId", (req, res) => {
const id = req.params.kpiId;
const name = req.body.kpiName;
const description = req.body.description;
const queryString = " UPDATE kpi_master SET kpiName = ? , description = ? WHERE kpiId = ? "
getConnection().query(queryString, [name, description, id], (err, results, fields, rows) => {
if (err) {
console.log("Not updated " + err);
res.sendStatus(500);
return
}
console.log('record updates ' + results.id)
res.send(results)
})
})
//create a new kpi
app.post('/user_create', (req, res) => {
console.log('Trying to create a new user...');
console.log('first name: ' + req.body.kpiName);
const kpiName = req.body.kpiName;
const description = req.body.description;
const queryString = 'INSERT INTO kpi_master (kpiName,description) values(?,?)';
getConnection().query(queryString, [kpiName, description], (err, results, fields) => {
if (err) {
console.log('Failed to insert new user :' + err);
res.sendStatus(500);
return;
}
console.log('Inserted a new user with id:', results.insertId);
res.end();
});
res.end();
});
app.get('/', (req, res) => {
console.log('Responding to root route');
res.send('Hello from ROOT');
});
//get kpi by single ID
app.get('/users/:kpiId', (req, res) => {
console.log('Fetching user with kpiId: ' + req.params.kpiId);
const connection = getConnection();
const userId = req.params.kpiId;
const queryString = 'SELECT * FROM kpi_master WHERE kpiId = ?';
connection.query(queryString, [userId], (err, rows, fields) => {
if (err) {
console.log('Failed to query for users: ' + err);
res.sendStatus(500);
return;
}
console.log('I think we fetched users successfully');
const users = rows.map((row) => {
return { kpiName: row.kpiName, description: row.description };
});
res.json(users);
});
// res.end()
});
//get kpi
app.get('/users', (req, res) => {
const connection = getConnection();
const queryString = 'SELECT * FROM kpi_master';
connection.query(queryString, (err, rows, fields) => {
if (err) {
console.log('Failed to query for users: ' + err);
res.sendStatus(500);
return;
}
res.json(rows);
});
});
const port = 5000;
app.listen(port, () => `Server running on port ${port}`);
It gives me the error as I've shared the image
I've made one datatable for listing records and on add we can add it through api. So now I've made api and add some records and made a file named server for api and it's working but i've called api in react form but can't able to list the api. As it shows this error...

I think your node_module for mysql is not installed in your node application. Kindly install it using
npm i mysql
and then restart your application again
Thank You.

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

API for making query searches not working

I'm trying to fetch all records from MongoDB starting with the Alphabet S but every time I try doing so, it returns nothing but []. I'm using the Params tab on Postman to do this.
The code that I have written is below as well as a snip from Postman to make the question more understandable. I'm pretty sure that the API I have written to perform this has something wrong with it.
The Model file
const mongoose = require('mongoose');
const entry = new mongoose.Schema({
name : {
type : String,
},
collegeName : {
type : String,
},
location : {
type : String,
}
});
const enter = mongoose.model("Student", entry);
module.exports = enter;
index.js
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const mongo = require('mongodb');
const dataModel = require('./model/model');
const MongoClient = mongo.MongoClient;
const uri = "mongodb+srv://coolhack069:XzC6N7dOyUeQl8M9#cluster0.kz6v9.mongodb.net/assignment?retryWrites=true&w=majority";
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });
app.use(express.json());
app.use(bodyParser.json());
const port = 3001;
app.get('/api/get', (req, res) => {
client.connect(err => {
if(err) {
throw err;
}
const collection = client.db('assignment').collection('data');
const fetchedData = {};
collection.find(fetchedData).toArray(function(err, result) {
res.send(result);
client.close();
});
})
});
app.get('/api/getStudentDetails', (req, res) => { //The API I have written to query through the Database
client.connect(err => {
if(err) {
throw err;
}
const collection = client.db('assignment').collection('data');
const fetchedData = new dataModel({
name : req.params.name
});
collection.find(fetchedData).toArray(function(err, result) {
res.send(result);
client.close();
})
})
});
app.post('/api/add', (req, res) => { //To add Data
const name = req.body.name;
const collegeName = req.body.collegeName;
const location = req.body.location;
client.connect(err => {
if(err) {
throw err;
}
const collection = client.db('assignment').collection('data');
const storeData = new dataModel({
name : name,
collegeName : collegeName,
location : location
});
console.log(storeData);
collection.insertOne(storeData, function(err, result) {
res.json({
result : "Success"
});
console.log(err);
client.close();
});
})
});
app.listen(port, () => {
console.log(`Application running at http://localhost:${port}`)
})
The Screenshot from Postman
Your find condition is not correct:
const fetchedData = new dataModel({ // ???
name : req.params.name
});
collection.find(fetchedData).toArray(function(err, result) {
res.send(result);
client.close();
})
??? - I guest your meaning is const fetchedData = { name: req.params.name}; - Find every document which have name is req.params.name (S - in your case). But there is no document has name is S in your collection, then it returns [].
If you want to find the documents with S as the first character of their name, you can use Regex syntax:
const query = {
name : new RegExp('^' + req.params.name, 'i'), // i - case insensitive, => /^S/i
};
collection.find(query).toArray(function(err, result) {
res.send(result);
client.close();
})

error while using deleteOne in app.delete function in 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)

Local Host not succesful

Command Shot
Above I have a screen shot of my app.js server and for some reason the connection is not going through below I have my app.js code
const express = require('express');
const app = express();
const mysql = require('mysql');
const bodyparser = require('body-parser');
app.use(bodyparser.json());
const mysqlConnection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'Adil#123',
database: 'movies'
});
mysqlConnection.connect(err=>{
if (err) {
console.log('It was not successful \n Error:' + JSON.stringify(err,undefined,2));
} else {
console.log('Its a success');
}
});
// Collecting all the movies from the movielist
app.get('/movielist',(req,res)=> {
mysqlConnection.query("SELECT * FROM movielist", (err, rows,fields)=> {
if (!err) {
res.send(rows);
} else {
console.log(err);
}
});
});
// Finding a movie based on the `idmovielist` number
app.get('/movielist',(req,res) => {
mysqlConnection.query("SELECT * FROM movielist WHERE idmovielist = ?",[req.params.id],(err, rows,fields) =>{
if (!err) {
res.send(rows);
} else {
console.log(err);
}
});
});
// Delting a movie
app.delete('/movielist/:id',(req,res) => {
mysqlConnection.query("DELETE FROM movielist WHERE idmovielist = ?",[req.params.id],(err,rows,fields) =>{
if (!err) {
res.send("Movie is deleted");
} else {
console.log(err);
}
});
});
// Inserting a movie
app.post('/movielist/addMovie',(req, res) => {
mysqlConnection.query("INSERT INTO movielist (`idmovielist`,`name`,`thumnail_path`,`description`,`language_released`,`year_released`) VALUES ('"+req.body.idmovielist+"', '"+req.body.name+"','"+req.body.thumnail_path+"', '"+req.body.description+"', '"+req.body.year_released+"', '"+req.body.language_released+"' )",
(err,rows) => {
if (!err) {
res.send("Movie is added");
} else {
console.log(err);
}
});
});
// Updating the movie list
app.put('/movielist/:id',(req,res) =>{
let update = req.body;
mysqlConnection.query("UPDATE movielist SET `year_released` WHERE = '"+update.idmovielist+"','"+update.year_released+"'",
(err, results) => {
if (!err) {
res.send("Movie list is updated");
} else {
console.log(err);
}
});
});
// localhost:3000
app.listen(3000,() => {
console.log('We got it running');
});
module.exports = app;
Above is my app.js the server was working earlier but for some reason it is not working anymore what can be the issue Is it something wrong with my code or should I change the port or create another server

Node/express postgresql stored procedure / function

I want to call a stored procedure / function in postgresql from node/express. I am using Angular 5.
Installed packages:
express: 4.16.2,
pg: ^7.4.0
Other required packages are also installed
Below is the code of my API - I want to replace all queries with my stored procedure / function call
const express = require('express');
const router=express.Router();
const {Pool,Client} = require('pg');
const connectionString = 'postgresql://postgres:1#localhost:5432/dbAngular'
// const client = new Client({
// connectionString:connectionString
// })
router.get('/employees', (err, res, done) => {
const client = new Pool({
connectionString:connectionString
})
client.connect((err)=>{
if(err!=undefined)
{
console.log('connection not established message as follow '+err.message+'')
}
});
client.query('select * from getEmployees();', (err, result) => {
if (err) {
console.log(err.stack) ;
client.end();
} else {
client.end();
console.log(result.rows);
res.json(result.rows);
}
})
})
//SAVE
router.post('/employees', (req, res,next) => {
const client = new Pool({
connectionString:connectionString
})
console.log( req.body);
var employee=req.body;
const query = {
text: 'INSERT INTO employes(name) VALUES($1)',
values: [employee.name]
}
client.connect((err)=>{
if(err!=undefined)
{
console.log('connection not established '+err.message+'')
}
});
client.query(query, (err, result) => {
if (err) {
console.log('ERRROOORRRRR');
client.end();
console.log(err.stack)
} else {
console.log('SAVEEEEE');
client.end();
// console.log(res.rows[0])
res.json();
}
})
});
//delete
router.delete('/employees/:id', (req, res,next) => {
const client = new Pool({
connectionString:connectionString
});
console.log('id passed is ' + req.param.id);
client.query('DELETE FROM employes WHERE empid=($1)',[req.param.id], (err, result) => {
if (err) {
console.log('ERRROOORRRRR');
client.end();
console.log(err.stack)
} else {
console.log('SAVEEEEE');
client.end();
// console.log(res.rows[0])
res.json();
}
});
});
module.exports=router;

Resources