I unknowingly sent a request twice with the same insert query which led to the same record being added twice. now when I'm trying to use the delete statement it's showing 'sending request' and is not moving forward.
but the delete statement is working if I try n delete any other record with does not have duplicate values. eg-
if I try using the delete statement on the record having request 1001, it isn't working, as there are 2 records with the same request_id.
but if I try to delete the record with the request id 1002, its working.
this is my code-
var express=require('express');
var router=express.Router();
var oracledb=require('oracledb');
router.post('/ins-rpt',function(req,res,next){
//get the data from req
const {stat,rid,rptcomp,reqr}=req.body;
//connect with db
var connectionString="(DESCRIPTION = (ADDRESS = (PROTOCOL = TCP)
(HOST = localhost)(PORT = 1521))(CONNECT_DATA =(SERVER
= DEDICATED)(SERVICE_NAME = orcl))"
oracledb.getConnection(
{
user: 'system',
password:'Valli1234',
tns:connectionString
}, async function(err,con){
if(err){
res.status(500).json({
message : 'not connected'
})
}
else{
//reqd opn
var q="delete from rpt where request_id=:1";
//send response
await con.execute(q,[],
{autoCommit:true},function(e,s){
if(e){
res.status(500).json({
message : e
})
}
else
{
res.status(200).json({
message : s
})
}
})
}
});
})
module.exports=router;
Related
I am newbie with node, express and Stackoverflow.
I have made a todo-list web application using nodejs , expressjs . it has following functions
In the home page of this web app you will get a Default list and In this default list you can add a new Item or delete an existing item
if you wish to create a New list you can create it dynamically by simply typing localhost/"new-list-name" on browser in which your app is running .again In this new list you can add and delete items
you can visit your Existing list by simply typing localhost/"existing-list-name" on browser in which your app is running . again In this existing list you can add and delete items
all this data get saved in MongoDB atlas.
The app was running very well but suddenly I am getting this following error whenever I am trying to create New list :-
Error: Failed to lookup view "/Tg" in views directory "C:\Users\himan\OneDrive\Desktop\udemyWeb\toDoList-v1\views"
In above error msg "/Tg" is the name of new list that I am trying to create.
Error
Error: Failed to lookup view "/Tg" in views directory "C:\Users\himan\OneDrive\Desktop\udemyWeb\toDoList-v1\views"
at Function.render (C:\Users\himan\OneDrive\Desktop\udemyWeb\toDoList-v1\node_modules\express\lib\application.js:597:17)
at ServerResponse.render (C:\Users\himan\OneDrive\Desktop\udemyWeb\toDoList-v1\node_modules\express\lib\response.js:1039:7)
at C:\Users\himan\OneDrive\Desktop\udemyWeb\toDoList-v1\app.js:145:16
at C:\Users\himan\OneDrive\Desktop\udemyWeb\toDoList-v1\node_modules\mongoose\lib\model.js:5213:18
at processTicksAndRejections (node:internal/process/task_queues:78:11)
folder structure screenshot
app.js
const express = require("express");
const bodyParser = require("body-parser"); //body-parser allows you to access req.body from within routes and use that data.
const { urlencoded } = require("express");
const mongoose = require('mongoose');// driver to integrate Node.js web-apps with MongoDB
const { redirect } = require("express/lib/response");
const _ = require("lodash");
const res = require("express/lib/response");
const app = express(); //allows to set-up middleware(here post & get request is acting as a middleware) to respond to HTTP requests.
const moduleDay = require(__dirname + "/date.js"); //exports desired functions and datas from the other files
// here functions of date.js file is getting exorted to app.js file
//var items = [];
var workItems = [];
app.use(express.urlencoded({extended:true})); //It parses the data coming from post request .
app.use(express.static(__dirname )); // Used to serve static files such as images, CSS files, and JavaScript files.
app.set('view engine', 'ejs');
// Mongoose or DataBase Section :-
main().catch(err => console.log(err));
async function main(){
// Establishing connection between DB and this webApp.
mongoose.connect("mongodb+srv://Himanshu:**Password**#cluster0.y4nquy6.mongodb.net/todolistDB");
//Schema or bluePrint of records in document
const itemsSchema = new mongoose.Schema({
Name: String
//, items : []
});
//Model(An isnstance of model is called a document)
const Item = mongoose.model("Item" , itemsSchema);
//Default items in the list
const Item1 = new Item ({
Name:"do exercise"
});
const Item2 = new Item ({
Name:"do learingng"
});
const Item3 = new Item ({
Name:"eat goodFoods"
});
const defaultitmes = [ Item1 ,Item2 , Item3];
const listSchema = {
Name:String,
items: [itemsSchema]
}
const List = mongoose.model("List", listSchema);
const day = moduleDay.getTime();
//........... Get route to root...........
app.get("/",function(req,res){
Item.find({},function(err,foundItems) {
if(foundItems.length === 0){
Item.insertMany(defaultitmes , function(err){
if(err){
console.log(err);
}else{
console.log("successfully saved default items to DB.");
}
res.redirect("/");
});
}
else
{
res.render("list" , {listTitle : day , newListItems : foundItems });
}
});
});
//.........Adding new items to the list or DB........
app.post('/',(req,res)=>{
const itemName = req.body.newItem;//new item you inserted in new/old list
const listName = req.body.list; // title of the new/old list
const item = new Item({
Name: itemName
});
if(listName === day){
item.save();
res.redirect("/");
}
else
{
List.findOne({Name:listName},function(err, foundList){
console.log( "This is foundList.items :- " + foundList.items);
foundList.items.push(item);
foundList.save();
res.redirect("/" + listName);
});
}
});
//dynamic routing with the help of express.js
app.get("/:coustomListName", function(req,res){
const coustomListName = _.capitalize(req.params.coustomListName);
console.log(coustomListName);
if(coustomListName === "Favicon.ico") return;
console.log(coustomListName + " line no. 131 ");
List.findOne({Name:coustomListName} , function(err,foundList){
if(!err)
{
if (!foundList){
//...........Create a new list on DB........
const list = new List({
Name: coustomListName ,
items : defaultitmes
});
list.save();
console.log("HEy folk! I am here on line no.->92 ");
res.render("/" + coustomListName );
}
else{
//..............Show up an existing list................
res.render("list.ejs", {listTitle: foundList.Name , newListItems: foundList.items});
// console.log(foundList.Name + "now item is :-" + foundItems.items)
}
}
});
});
app.get("/about", (req,res)=>{
res.render("about");
})
app.post('/delete',function(req,res){
const checkedItemid = req.body.checkbox;
const listName = req.body.listName;
if (listName === day)
{
Item.findByIdAndRemove(checkedItemid,function(err){
if(!err){console.log("deleted successfully !!!");}
res.redirect('/');
});
}
else{
List.findOneAndUpdate({Name: listName},{$pull :{items: {_id : checkedItemid}}},(err,foundList)=>{
if(!err){
res.redirect("/"+ listName);
}
})
}
});
}
app.listen(80,function(){
console.log("port started at local host 80");
});
I would be thankful if some one can fix this error and explain it.
i am beginner in node.js and i noticed that after i execute my request the first time it works but node.js launch an error after it that says:
Can not set headers after they are sent to client
Here what i have tried
questions service:
module.exports={
create:(data,callback)=>{
var myArray = new Array();
/* for(let item of data.players) {
console.log(item.firstname);
}*/
console.log(data);
data.players.forEach((player) => {
console.log(player.id);
console.log(player);
var playerModel ={
id : player.id,
firstname : player.firstname,
lastname : player.lastname,
position : player.position,
price : player.price,
appearences : player.appearences,
goals : player.goals,
assists : player.assists,
cleansheets : player.cleansheets,
redcards : player.redcards,
yellowcards : player.yellowcards,
image : player.image
};
console.log("model"+playerModel.position);
myArray.push(playerModel);
});
var id;
pool.query(
'insert into club(userid,email,password,name,price) values(?,?,?,?,?)',
[
data.userid,
data.email,
data.password,
data.name,
data.price
],
(error,result) => {
if(error){
callback(error);
}
for(var item of myArray){
pool.query(
'insert into players(id,firstname,lastname,position,price,appearences,goals,assists,cleansheets,redcards,yellowcards,image,clubid) values (?,?,?,?,?,?,?,?,?,?,?,?, ( SELECT id from club where id > ? ORDER BY id DESC limit 1 ) )',
[
item.id,
item.firstname,
item.lastname,
item.position,
item.price,
item.appearences,
item.goals,
item.assists,
item.cleansheets,
item.redcards,
item.yellowcards,
item.image,
0
],
(error,results,fields)=>{
if(error){
callback(error);
}
return callback(null,results);
},
);
}
return callback(null,result.insertId);
},
);
},
Questions Controller:
const pool = require("../../config/database");
const{create,
getQuestionsById,
getQuestionsByCategory,
getQuestions,
getValidAnswer,
setValide,
CompareAnswers,
updateQuestions,
deleteQuestions
}=require("./questions.service");
module.exports={
createQuestions:(req,res)=>{
const body = req.body;
create(body,(err,results)=>{
if(err){
console.log(err);
return res.status(500).json({
success:0,
message:"database connexion error"
});
}
return res.status(200).json({
success:1,
data:results
});
});
},
Questions router:
const{
createQuestions,
getQuestionsById,
getQuestions,
getQuestionsByCategory,
getValidAnswer,
CompareAnswers,
setValide,
updateQuestions,
deleteQuestions,
}=require("./questions.controller");
const router = require("express").Router();
router.post("/addQuestion",createQuestions);
router.get("/:id",getQuestionsById);
router.patch("/updateQuestion",updateQuestions);
router.delete("/",deleteQuestions);
router.get("/",getQuestions);
router.get("/VerifyAnswer/:id",getValidAnswer);
router.post("/getByCategory",getQuestionsByCategory);
router.post("/setValide", setValide);
router.post("/CompareAnswers", CompareAnswers);
module.exports=router;
My goal is to stop this error and find a solution for it, What is wrong with my code ? and why i have to run again the server after every execute of the request?? why the request works but it launch this error in the end?
A screen capture that shows the error:
I think in your question service in line:
(error,results,fields)=>{
if(error){
callback(error);
}
you should write
return callback(error)
This error generally occurs when your code tries to send 2 or more responses for a request. Let me know if it helps.
i really don't know what it could be a problem but everytime i try to post i get a log error : ER_BAD_NULL_ERROR: Column 'idmedecin' cannot be null
i've seen allot of similar questions (trouble in post req) but nothing solved my problem and i cannot see what im doing wrong since idmedcin is clearly not NULL
reqLink used = http://..***.107:3000/rendezvousinsert?idmedecin=1&idpatient=1&date=546654&etat=1
const mysql = require('mysql');
const express = require('express');
var app = express();
const bodyparser = require('body-parser');
app.use(bodyparser.json());
var mysqlConnection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '',
database: 'pim',
multipleStatements: true
});
mysqlConnection.connect((err) => {
if (!err)
console.log('DB connection succeded.');
else
console.log('DB connection failed \n Error : ' + JSON.stringify(err, undefined, 2));
});
app.listen(3000, () => console.log('Express server is runnig at port no : 3000'));
app.post('/rendezvousinsert/',(req,res)=> {
var post= {
idmedecin : req.body.idmedecin ,
idpatient : req.body.idpatient ,
date : req.body.date ,
etat : req.body.etat
};
mysqlConnection.query('INSERT INTO rendezvous SET ?' , post, function(error) {
if (error) {
console.log(error.message);
} else {
console.log('success');
}
});
});
here is my table structure
You're sending data through query string http://..***.107:3000/rendezvousinsert?idmedecin=1&idpatient=1&date=546654&etat=1 but trying to access it through req.body
idmedecin=1&idpatient=1&date=546654&etat=1 This data is available as
req.query.idmedecin // 1
req.query.idpatient // 1
req.query.date // 546654
// etc
You are trying to get the fields from the request body, but in your example you send them as query params.
I think the correct way is to send the object inside the POST body and not as query params, but if you want the request to remain as in your example, it should look like this:
var post= {
idmedecin : req.query.idmedecin ,
idpatient : req.query.idpatient ,
date : req.query.date ,
etat : req.query.etat
};
i created a node.js code that listen to sql server and access it database and im trying to run the code on browser using "http://localhost:1433/test" but it always giving men this
this is my node.js code:
const uid = require('uuid');
const express = require('express');
const bodyParser = require('body-parser');
const sql = require('mssql');
const driver = require('msnodesqlv8');
const config = {
// multipleStatements: true, TO EXECUTE MORE THAN ONE QUERY IN ONE STATEMENT
//driver: 'msnodesqlv8',
server: 'MOSTAFA',
user: 'admin',
password: 'mostafabaron123#',
database: 'WholeSale',
options:{
trustedConnection: true,
useUTC: true,
}
};
const userExistCode = 200;
const buyerCreatedCode = 400;
const buyerNotCreatedCode = 401;
const sellerCreatedCode = 500;
const sellerNotCreatedCode = 501;
const connectionErrCode = 100;
var app = express();
app.use(bodyParser.json()); // accept JSON parms
app.use(bodyParser.urlencoded({extended:true}));
// bueyer signup part
app.post('/buyerSignUp', function(req, res) {
var postData = req.body; // get post params
var userId = uid.v4();
sql.connect(config, (err)=>{
if(err){
console.log('not connected');
return;
}
var request = new sql.Request();
request.input('email', sql.VarChar(45), postData.email)
.input('password', sql.VarChar(45), postData.password)
.input('category', sql.VarChar(45), postData.category)
.query('select * from Buyer where email = #email and category = #category
and password = #password'
, (err, recordSet)=>{
if(recordSet.length == 1){
res.status(userExistCode).send("Buyer already exists.");
}else{
new sql.Request()
.input('buyerId', sql.VarChar(45), userId)
.input('firstName', sql.VarChar(45), postData.firstName)
.input('lastName', sql.VarChar(45), postData.lastName)
.input('email', sql.VarChar(45), postData.email)
.input('password', sql.VarChar(45), postData.password)
.input('phoneNumber', sql.VarChar(45), postData.phoneNumber)
.input('category', sql.VarChar(45), postData.category)
.query('insert into Buyer(buyer_id, first_name, last_name, email,
password, phone_number, category) values(#buyerId, #firstName,
#lastName, #email, #password, #phoneNumber, #category)'
, (err, recordSet)=>{
if(err){
console.log(err);
return;
}
if(recordSet.length == 1){
res.status(buyerCreatedCode).send("Account Created as Buyer.");
}else{
res.status(buyerNotCreatedCode).send("Account not Created as
Buyer.");
}
});
}
});
});
});
app.listen(1433, ()=>{
console.log('server is running on 1433...');
});
what i expect to see the messages if the user created or already existed.
anyone can explain why this is happening?
Just from reading your code, here is what I suspect is happening: you are starting up express and listening to port 1433. It does successfully call your listening callback and print the appropriate console.log statement, so we know it gets that far.
Then, you attempt to connect to your database. Your database port is also 1433, which we know is not correct (the database port cannot be the same as your express port, if it was, express would never have started). So your connection to the database fails.
The database connection callback checks for an error, then returns. This means you'll never see the "connected" console.log statement, and you'll never actually create the route for /buyerSignup. Basically, your app is running, but has no useful routes.
(I'm not sure what you even expect to see at the URL /test -- nothing in this code snippet shows you creating that route. But, you'll need to fix the issues above in any case.)
I'm making a call to the server using resource and when I go to the base URL of
/viewEvent
It works fine. I receive all the database entries. However, when I go to
/viewEvent/1234
where 1234 is the eventID
I get a undefined is not a function and this is a crash from within angular. Stack trace is
TypeError: undefined is not a function
at copy (http://localhost:8000/js/lib/angular/angular.js:593:21)
at http://localhost:8000/js/lib/angular/angular-resource.js:410:19
at wrappedCallback (http://localhost:8000/js/lib/angular/angular.js:6846:59)
at http://localhost:8000/js/lib/angular/angular.js:6883:26
at Object.Scope.$eval (http://localhost:8000/js/lib/angular/angular.js:8057:28)
at Object.Scope.$digest (http://localhost:8000/js/lib/angular/angular.js:7922:25)
at Object.Scope.$apply (http://localhost:8000/js/lib/angular/angular.js:8143:24)
at done (http://localhost:8000/js/lib/angular/angular.js:9170:20)
at completeRequest (http://localhost:8000/js/lib/angular/angular.js:9333:7)
at XMLHttpRequest.xhr.onreadystatechange (http://localhost:8000/js/lib/angular/angular.js:9303:11) angular.js:575
When I examine the server, the request was made correctly. I can see that it got 1234 and it pulls the correct entry from the mongo database.
This is the controller logic
.controller("viewEventsController", ["$scope", 'EventService', '$location', function($scope, EventService, $location){
var path = $location.path().split('/');
var pathSize = path.length;
$scope.events = [];
if(pathSize === 2){
console.log("No event ID");
$scope.events = EventService.query();
}
else{
console.log("Event ID specified");
EventService.get({"eventID": path[pathSize - 1]}, function(data){
//$scope.events.push(data);
console.log(data);
}, function(error){
console.log(error);
});
}
}]);
and the service logic
service.factory('EventService', function($resource){
return $resource('api/viewEvent/:eventID');
});
It never makes it back to the controller so I'm "confident" it's not that. (watch it be that)
Not sure if the best way, but I got it working by doing
In service:
service.factory('EventService', function($resource){
return $resource('api/viewEvent/:eventID',
{eventID:"#eventID"},
{
'getSingleEvent': {
url: "api/viewEvent/:eventID",
method: "GET",
isArray: true
}
}
);
controller
var path = $location.path().split('/');
var pathSize = path.length;
EventService.getSingleEvent({"eventID":path[pathSize - 1]}, function(result){
$scope.updateEvent();
});
Server
routes = require('./routes')
var router = express.Router();
router.get('/api/viewEvent/:eventID', routes.viewEvent);
and in the routes directory I have a js file with
var mongoose = require('mongoose');
var db = mongoose.createConnection('localhost', 'eventApp');
var eventSchema = require('../models/createEvent.js').eventSchema;
var event = db.model('events', eventSchema);
exports.viewEvent = function(req, res){
console.log(req.params.eventID);
if(req.params.eventID) {
event.find({"_id": req.params.eventID}, function (error, events) {
console.log(events);
res.send(events);
});
}
else{
event.find({}, function (error, events) {
console.log(events);
res.send(events);
})
}
};