modify query function in Sequelize - node.js

I'm learning "Sequelize".
I went through documentation and got this code somewhere else.
Model = require('../models/Salesman')
module.exports.creareSalesman = (req, res, next) => {
Model.create(req.body).then(
result => {
res.status.json({data: result})
}).catch(err => console.log(err))
}
but I want this in the below structure,
Model = require('../models/Salesman')
module.exports.creareSalesman = (req, res, next) => {
Model.create(req.body, function (result, err) {
if (err) {
console.log(err)
}
else {
res.status.json({data: result})
}
});
}
I tried this,.it didn't send the response. But inserted the data correctly to db.
How to get the response in this case.?

The Model.create method returns a Promise, and does not have a callback parameter.
So you either handle the Promise with then:
module.exports.creareSalesman = (req, res, next) => {
Model.create(req.body)
.then((result) => {
res.status.json({ data: result });
})
.catch((err) => console.log(err));
};
Or use async await:
module.exports.creareSalesman = async (req, res, next) => {
try {
const result = await Model.create(req.body);
res.status.json({ data: result });
} catch (err) {
console.log(err);
}
};

Related

How to redirect/render to 404 if the "_id" is wrong/misspelled in /blogs/:blogId

I want to redirect users to "404.ejs" if the post id is entered wrong/mispelled in blogs/:blogId route. How can I accomplish it in below code.
app.get('/blogs/:blogid', (req, res) => {
const requestedId = req.params.blogid;
Blog.findById(requestedId, (err, addedblogpost) => {
if (err) {
console.log(err);
}
else {
res.render("post", {
title: addedblogpost.blogTitle,
content: addedblogpost.blogContent
})
}
})
}
Code for "404"
app.get('*', (req, res) => {
res.render('404');
})
You should make use of express next parameter to get the result you want.
This will call the next "matching" middleware for the current route, assuming this would be your error handler middleware of course.
It should be used as shown below :
app.get('/blogs/:blogid', (req, res, next) => {
const requestedId = req.params.blogid;
Blog.findById(requestedId, (err, addedblogpost) => {
if (err) {
next();
}
else {
res.render("post", {
title: addedblogpost.blogTitle,
content: addedblogpost.blogContent
})
}
})
Express doc : https://expressjs.com/en/guide/using-middleware.html
app.get('/blogs/:blogid', async (req, res) => {
const requestedId = req.params.blogid;
const blog = await Blog.findById(requestedId);
if (!blog) return res.render("404");
res.render("post");
}
to check if the blog is null or not.

Subscribe method does not work in angular

product-operations.component.ts
deleteProduct() {
this.productsService.delete_product(this.deleteID).subscribe((res: any) => {
console.log("helloooooo");
});
};
product.service.ts
delete_product(id) {
return this.http.delete("http://localhost:3000/delete_product/" + id);
}
backend
exports.deleteProduct = (req, res, next) => {
const id = req.param("id");
Product.deleteOne({ _id: id })
.then(() => {
console.log("deleted");
})
.catch(err => {
console.log(err);
});
};
Problem:
In the above codes, the deleteProduct function in product-operations.component.ts doesn't work properly. More precisely, it does the removal. But after doing the uninstall, subscribe doesn't run its contents. This prevents my instant update after deletion. How can I solve this?
Try to send a response back from the server.
exports.deleteProduct = (req, res, next) => {
const id = req.param("id");
Product.deleteOne({ _id: id })
.then(() => {
res.send({}) // or res.send({id: id})
console.log("deleted");
})
.catch(err => {
res.status(500)
res.send({error: err})
console.log(err);
});
};

NodeJS / Express: inconsistent [ERR_HTTP_HEADERS_SENT] occurring

Here I have a POST method that gets called quite often.
app.post('/return_data', async (req, res) => {
var response, file
console.log("request recieved: " + req.body.room)
await readFile('Data/'+req.body.room+'.json').then((data) => {
console.log(data)
return res.send(data)
}).catch((e) => {
console.log(e)
})
})
For some reason the response is intermittent. Sometimes it will log the following error.
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
at ServerResponse.setHeader (_http_outgoing.js:535:11)
at ServerResponse.header (/home/ec2-user/dc-floorplans/node_modules/express/lib/response.js:771:10)
at ServerResponse.send (/home/ec2-user/dc-floorplans/node_modules/express/lib/response.js:194:10)
at /home/ec2-user/dc-floorplans/app.js:127:13
at processTicksAndRejections (internal/process/task_queues.js:97:5)
at async /home/ec2-user/dc-floorplans/app.js:125:5 {
code: 'ERR_HTTP_HEADERS_SENT'
}
When I first start my web app, usually the first POST logs an error. After refreshing the page, the data comes through as intended. There is only one response in the function and so I'm puzzled as to why this error is occurring.
I know that readFile works because the data is logged in .then(). How can it be that sometimes data is sent to the client and other times it throws an error when the exact same process is happening?
Thanks in advance.
UPDATE -- FULL APP.JS:
app.set('view-engine', 'ejs');
app.use(express.urlencoded({ extended: false }))
app.use(cors())
app.use(flash())
app.use(session({
secret: process.env.SESSION_SECRET,
resave: false,
saveUninitialized: false
}))
app.use(passport.initialize())
app.use(passport.session())
app.use(methodOverride('_method'))
app.use(express.static(__dirname + '/static'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.get('/', checkAuthenticated, (req, res) => {
res.render('index.ejs');
});
app.get('/login', checkNotAuthenticated, function(req, res, next) {
res.render('login.ejs');
});
app.post('/login', checkNotAuthenticated, (req, res, next) => {
passport.authenticate('local', (err, user, info) => {
if(err) throw err
if(!user) return res.redirect('/login')
req.logIn(user, (err) => {
if(err) return next(err)
if(info.message==process.env.DEFAULTPW) {
console.log("Default password detected for: " + user.email)
return res.redirect('/')
}
return res.redirect('/')
})
})(req, res, next)
})
app.get('/update', checkAuthenticated, (req, res, next) => {
res.render('update.ejs')
})
app.post('/update', checkAuthenticated, async (req, res, next) => {
if(req.body.pw1 != req.body.pw2) { res.redirect('/update') }
if(req.body.pw2 == process.env.DEFAULTPW) { res.redirect('/update') }
const newpw = await encrypt(req.body.pw2)
var queryresult
await con.query("UPDATE login SET password = \'"+newpw+"\' WHERE email = \'"+req.body.email.toLowerCase()+"\'", (err, result, fields) => {
if (err) {
console.log(err)
return res.redirect('/update')
};
console.log(result)
queryresult = result
if(result.changedRows == 0) {
return res.redirect('/update')
}
})
return res.redirect('/')
});
app.post('/get_new_data', async (req, res) => {
console.log("New Data:")
await pollLM(req.body.room).then((data) => {
console.log(data)
return res.send(data)
}).catch((e) => {
console.log(e)
})
})
async function pollLM(room) {
return new Promise((resolve, reject) => {
const getData = pySpawn('python3.7', ['getData.py', room])
getData.stdout.on('data', (data) => {
resolve(data)
})
})
}
app.post('/return_data', async (req, res) => {
console.log("request recieved: " + req.body.room)
await readFile('Data/'+req.body.room+'.json').then((data) => {
console.log(data)
return res.send(data)
}).catch((e) => {
console.log(e)
})
})
async function readFile(path) {
return new Promise((resolve, reject) => {
fs.readFile(path, (err, data) => {
if (err) reject(err);
console.log(typeof(data))
resolve(data)
})
})
}
app.post('/update_reload_time', (req, res) => {
console.log("reload time updated to: " + req.body.time)
fs.writeFile('Data/delay.json', JSON.stringify(req.body), () => {
console.log("delay updated to: " + req.body.time)
})
})
app.get('/reload_time', async (req, res) => {
await readFile('Data/delay.json').then((data) => {
console.log(data)
return res.send(data)
}).catch((e) => {
console.log(e)
})
})
app.delete('/logout', (req, res) => {
req.logOut()
res.redirect('/login')
})
// Page routing...
function checkAuthenticated(req, res, next) {
if(req.isAuthenticated()) {
return next()
}
res.redirect('/login')
}
function checkNotAuthenticated(req, res, next) {
if(req.isAuthenticated()) {
return res.redirect('/')
}
next()
}
function encrypt(text) {
const key = crypto.scryptSync(process.env.CRYPTOPW, process.env.SALT, 24)
const cipher = crypto.createCipher('aes-192-cbc', key)
let encrypted = ''
cipher.on('readable', () => {
let chunk
while(null != (chunk = cipher.read())) {
encrypted += chunk.toString('hex')
}
})
cipher.write(text)
cipher.end()
return encrypted
}
function decrypt(text) {
const key = crypto.scryptSync(process.env.CRYPTOPW, process.env.SALT, 24)
const decipher = crypto.createDecipher('aes-192-cbc', key)
let decrypted = '';
decipher.on('readable', () => {
while(null !== (chunk = decipher.read())) {
decrypted += chunk.toString('utf8')
}
})
const encrypted = text
decipher.write(encrypted, 'hex')
decipher.end()
return decrypted
}
All you have to look for is where you response twice on the same call.
For example:
app.post('test', (req,res)=>{
res.send('1')
res.json('{1:2}')
})
will always return this error, because you are responding twice.
You have to investigate your routes one by one, I would start here:
app.post('/update', checkAuthenticated, async (req, res, next) => {
if(req.body.pw1 != req.body.pw2) { res.redirect('/update') }
if(req.body.pw2 == process.env.DEFAULTPW) { res.redirect('/update') }
const newpw = await encrypt(req.body.pw2)
var queryresult
await con.query("UPDATE login SET password = \'"+newpw+"\' WHERE email = \'"+req.body.email.toLowerCase()+"\'", (err, result, fields) => {
if (err) {
console.log(err)
return res.redirect('/update')
};
console.log(result)
queryresult = result
if(result.changedRows == 0) {
return res.redirect('/update')
}
})
return res.redirect('/')
});
You are calling res.redirect explicitly and on condition. Have you checked if both conditions meet simultaneously? I guess here is one weak point.
And I would check this one
app.post('/login', checkNotAuthenticated, (req, res, next) => {
passport.authenticate('local', (err, user, info) => {
if(err) throw err
if(!user) return res.redirect('/login')
req.logIn(user, (err) => {
if(err) return next(err)
if(info.message==process.env.DEFAULTPW) {
console.log("Default password detected for: " + user.email)
return res.redirect('/')
}
return res.redirect('/')
})
})(req, res, next)
})
Again there potentially meet two conditions. Check them out. Other parts look fine to me.

Node/Express Route 'Show' presenting too many results

This is for the backend of a MEAN site.
I am currently trying to create several search functions based off of different params in the same mongoose model. For the Controller I have
show:(req,res) => {
Activity.findById
({_id: req.params._id}).then(activity => {
res.json(activity)
})
.then(console.log(req.query._id))
},
show: async (req, res, next) => {
const linkClicked = await Activity.find
({linkClicked: req.params.linkClicked})
.then(result => {
res.send(result)
})
.then(next())
.catch(err => (console.log(err)))
},
show:(req,res, next) => {
Activity.find({caseAssigned: req.params.caseAssigned}).then(action => {
res.json(action)
next()
})
.catch(err => (console.log(err)))
},
show:(req,res, next) => {
Activity.find({addedToQue: req.params.addedToQue}).then(activity => {
res.json(activity)
next()
})
.catch(err =>(console.log(err)))
},
show:(req, res, next) => {
Activity.find({statusChanged: req.params.statusChanged}).then(activity => {
res.json(activity)
next()
})
.catch(err => (console.log(err)))
},
show:(req,res) => {
Activity.findById
({_id: req.params._id}).then(activity => {
res.json(activity)
})
.then(console.log(req.query._id))
},
show: async (req, res, next) => {
const linkClicked = await Activity.find
({linkClicked: req.params.linkClicked})
.then(result => {
res.send(result)
})
.then(next())
.catch(err => (console.log(err)))
},
show:(req,res, next) => {
Activity.find({caseAssigned: req.params.caseAssigned}).then(action => {
res.json(action)
next()
})
.catch(err => (console.log(err)))
},
show:(req,res, next) => {
Activity.find({addedToQue: req.params.addedToQue}).then(activity => {
res.json(activity)
next()
})
.catch(err =>(console.log(err)))
},
show:(req, res, next) => {
Activity.find({statusChanged: req.params.statusChanged}).then(activity => {
res.json(activity)
next()
})
.catch(err => (console.log(err)))
},
For the routes I have:
const express = require('express');
const controllerRouter = express.Router();
const activityController = require("../controllers/activity")
controllerRouter.get("/", activityController.index)
// controllerRouter.get("/search/:_id", activityController.show)
controllerRouter.get("/event/:linkClicked/linkClicked/", activityController.show)
controllerRouter.get("/event/caseAssigned/:caseAssigned", activityController.show)
controllerRouter.get("/event/addedToQue/:addedToQue", activityController.show)
controllerRouter.get("/event/statusChanged/:statusChanged", activityController.show)
When I search in postman for /event/true/linkClicked I receive JSON that does not have linkClicked:true.
Solutions I have tried:
1) I tried implementing the next() function in my controller and adding async capability. I'm not sure if I implemented this correctly. I've made sure that my JSON data is accurate.
Any help is appreciated. (Also, this is my first post so if I have left out a necessary detail, please, let me know.)

Do I need to return the promise from the entry point of my application?

In express, I have the following code:
app.get('/hello', (req, res) => {
return controller.doSomthingAsync(req).then(() => {
res.send({message: "Hello World"});
})
});
However, I can also do
app.get('/hello', (req, res) => {
controller.doSomthingAsync(req).then(() => { // Return removed
res.send({message: "Hello World"});
})
});
The above also works, but I was wondering if there is any difference between the 2 approaches, and can the second one cause any problems?
Considering the piece of code you provided, there is no difference in using the two versions.
The only benefit of that return is that any piece of code you put after that would not be executed. For instance, suppose the following piece of code:
app.get('/hello', (req, res) => {
if (req.query.foo === 'bar') {
controller.doSomethingAsync(req).then(() => {
res.send({message: "Hello World"});
}).catch(err => {
console.log(err);
res.status(500).send(err);
});
}
controller.doSomethingElseAsync(req).then(() => {
res.send({message: "Hello Universe"});
}).catch(err => {
console.log(err);
res.status(500).send(err);
});
});
This would produce an error since both of the async operations would be performed and try to send the response.
Adding a return in the if block would prevent executing the second async operation and the error.
app.get('/hello', (req, res) => {
if (req.query.foo === 'bar') {
return controller.doSomethingAsync(req).then(() => {
res.send({message: "Hello World"});
}).catch(err => {
console.log(err);
res.status(500).send("Error");
});
}
controller.doSomethingElseAsync(req).then(() => {
res.send({message: "Hello Universe"});
}).catch(err => {
console.log(err);
res.status(500).send("Error");
});
});
EDIT: As Bergi pointed out, using else would do the job as well and avoid to return something that express can't handle.
app.get('/hello', (req, res) => {
if (req.query.foo === 'bar') {
controller.doSomethingAsync(req).then(() => {
res.send({message: "Hello World"});
}).catch(err => {
console.log(err);
res.status(500).send("Error");
});
} else {
controller.doSomethingElseAsync(req).then(() => {
res.send({message: "Hello Universe"});
}).catch(err => {
console.log(err);
res.status(500).send("Error");
});
}
});
No, you don't need to return a promise from your express route, as express does not know what to do with promises (a pity!).
However, every time you call a promise-returning function and do not do further chaining and returning it to your caller, i.e. when you end a promise chain, you are responsible for handling errors from it. So it would be appropriate to do
app.get('/hello', (req, res) => {
controller.getMessageAsync(req).then(msg => {
res.status(200).send(msg);
}, err => {
console.error(err);
res.status(500).send("Sorry.");
});
});

Resources