anyone can help me to find the problem ?
I've tried to update data in users table in postgres-db. This code doesn't sent error message or anything, when I tried to check code in Postman like this (see below) I got success message, but data in database doesn't change at all.
router.post('/testedit/:userid', (req, res) => {
let sql = 'UPDATE users SET firstname=$1, lastname=$2, position=$3, type=$4, isadmin=$5 WHERE userid=$6'
db.query(sql, [req.body.firstname, req.body.lastname, req.body.position, req.body.type, req.body.isadmin, req.params.userid], (err, data) => {
if (err) console.log(err);
res.json({
message: 'update success'
})
})
})
Related
I've tried some methods but nothing works
and I'm trying to change
Anyone can give me a little trick to create this function in node js?
Your suggestions will be very helpful for me to solve it
//router_register.js
// Definisikan router dari express
const router = require('express').Router();
// Ambil index.js dari controller dan panggil variabel didalamnya
const registerController = require('../controllers').register;
// Definisikan middleware verify.js
const verifyUser = require('../configs/verify');
// Rute 'http://localhost:5050/register/' digunakan untuk menampilkan form register
router.get('/', verifyUser.isLogout, registerController.formRegister);
// Rute 'http://localhost:5050/register/save' digunakan untuk menyimpan data yang diinput user saat register
router.post('/save', verifyUser.isLogout, registerController.saveRegister);
// Export agar dapat dibaca oleh express
module.exports = router;
//controller_register
const config = require('../configs/database');
let mysql = require('mysql');
let pool = mysql.createPool(config);
pool.on('error', (err)=> {
console.error(err);
});
module.exports = {
formRegister(req, res) {
res.render("login", {
// Definisikan semua varibel yang ingin ikut dirender kedalam register.ejs
url: 'http://localhost:5050/',
});
},
saveRegister(req, res) {
let username = req.body.username;
let email = req.body.email;
let password = req.body.pass;
if (username && email && password) {
pool.getConnection(function(err, connection) {
if (err) throw err;
connection.query(
`INSERT INTO table_user (user_name, user_email, user_password) VALUES (?,?,SHA2(?,512)); `, [username, email, password], function (error, results) {
if (error) throw error;
req.flash('color', 'success');
req.flash('status', 'Yes..');
req.flash('message', 'Registrasi berhasil');
res.redirect('/login');
});
connection.release();
})
} else {
res.redirect('/login');
res.end();
}
}
}
And please tell me which parts I should fix to make it even better for this coding
You have a couple of options. May be even both to get a robust solution. As you asked for general direction, instead of giving you exact code, I will try to point you in right direction.
In your saveRegister function, before you run INSERT, using email, you can run another query to fetch any existing user's with the incoming email address. If you find one, throw an exception for user trying to register with existing email.
To make this even better, you can add a UNIQUE constraint on your table in the database for the user_email column. This way if you do try to save another user with a duplicate email, you should get an exception that your try block will catch.
All the best. Please update the question with specifics if you try this approach and still need more help.
I encountered a weird bug when doing a quick coding assignment.
Here is my code.
Lets call this 'A'
//Grab all the animals from the database
WebApp.get('/all',(req,res) =>
{
const connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '1234', //Enter your password here
// I found that mySQL 8.0 uses a new default authent plugin whereas 5.7 uses a different one, If you get a ER_NOT_SUPPORTED_AUTH_MODE error from the response, try referring to this post to alter your root password. (https://stackoverflow.com/questions/50373427/node-js-cant-authenticate-to-mysql-8-0)
database: 'animals'
});
const query = "SELECT * FROM animals";
connection.query(query, (err, rows, fields) =>
{
if (err)
{
console.error('error : ' + err.stack);
res.sendStatus(500);
return;
}
console.log("Fetched animals successfully");
//console.log(rows); // Use this for error checking to see if a authent problem occurs.
res.json(rows);
});
});
and this 'B'
//Grab a selected animal from the database given a valid Id.
WebApp.get('/:id',(req,res) =>
{
console.log("Fetching user with id: " + req.params.id);
const connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '1234', //Enter your password here
// I found that mySQL 8.0 uses a new default authent plugin whereas 5.7 uses a different one, If you get a ER_NOT_SUPPORTED_AUTH_MODE error from the response, try referring to this post to alter your root password. (https://stackoverflow.com/questions/50373427/node-js-cant-authenticate-to-mysql-8-0)
database: 'animals'
});
const animalId = req.params.id;
const query = "SELECT * FROM animals WHERE id = ?";
connection.query(query, [animalId], (err, rows, fields) =>
{
if (err)
{
console.error('error : ' + err.stack);
res.sendStatus(500);
return;
}
console.log("Fetched animals successfully");
//console.log(rows); // Use this for error checking to see if a authent problem occurs.
res.json(rows);
});
});
For some reason, if I put A before B it works, and I get successful results from my queries. However, if I put B before A, B will return successfully, but A will return '[]'. Anyone know why?
Thanks for any help!
Have you tried terminating the connection after each request, or considered using a connection pool? I am not familiar with nodeJS integration with MySQL, but in SQLServer, it is best to use ConnectionPool, when asynchronously making database requests.
I am trying to get the lastly inserted _id from a MongoDB document. I am not sure how to do this, here is what I tried.
I need to send the _id using res.status(200).send(id)
Here is what I tried so far...
router.route("/last/inserted/assignment/id").get((req, res) => {
AssignmentDB.find({})
.sort({ _id: -1 })
.limit(1);
});
You can do this by getting a document according to when it was created...
router.get("/last/inserted/assignment/id", (req, res) => {
AssignmentDB.findOne().sort({createdAt: -1}).exec(function(err, post) {
if (err) {return err}
console.log(post)
});
Also NOTE The other mistake I've correctd in your code. You should correct that too.
This is my first time working with node and postgre. I am trying to get the email, first name, and last name from my postgre database by passing in a user's email address in a SQL statement:
function getSingleUser(req, response, next){
var UserId = req.params.email.substring(1);
console.log(UserId);
pool.connect(function(err, client, done){
if(err){
return console.error('Error fetching client from pool', err);
}
client.query('SELECT users.email, users.firstname, users.lastname, users.id FROM people.users WHERE users.lastname = Williams', function(err, results){
if(err){
return console.log('error running query', err);
}
// Just returns the raw json data
response.json(results.rows);
client.release();
done();
});
});
};
Whenever I run this though I get the error: error running query { error: column "williams" does not exist. So what can I use to check for a value and not a column? Thank you
Ok I fixed it by adding single quotes around my parameter and double quotes around everything else.
client.query("SELECT users.email, users.firstname, users.lastname, users.id FROM people.users WHERE users.lastname = '" + UserId + "'"
I'm using Node.js/Express.js to install data to my MySQL DB.
Inserting data works fine, but returning success / fail gives me an error.
TypeError: Cannot read property 'status' of undefined
This is my code:
var crud = {
newProject: function (req, res, callback) {
db.query('INSERT INTO projects SET ?', req.body, function(err, res) {
// This is where it fails
if(err){
return res.status(500).json({error: err});
} else {
return res.status(200).json({success: 'Insert row success'});
}
});
},
}
// Express routing
app.post('/project/*', crud.newProject);
What am I not getting right here?
Solution
So this is what I used to make it work (after changing 'res' to 'resp' as suggested):
if (err) throw err;
res.end(JSON.stringify({response: 'Success'}));
Your defining res twice. The express response object is getting overwritten by the data param in your node callback.
Try the following (see comment)
var crud = {
newProject: function (req, res, callback) {
// changed 'res' to 'resp' to avoid collision with Express' 'res' object
db.query('INSERT INTO projects SET ?', req.body, function(err, resp) { // here's your error
// This is where it fails
if(err){
return res.status(500).json({error: err});
} else {
return res.status(200).json({success: 'Insert row success'});
}
});
},
}
// Express routing
app.post('/project/*', crud.newProject);
If you define error-handling middleware functions after the last app.use() in your main configuration
app.use(function (err, req, res, next) {
res.status(500).send(err.message || 'Internal server error.')
})
You can use the next callback as a catchall error handler, so the above would then become
var crud = {
newProject: function (req, res, callback) {
db.query('INSERT INTO projects SET ?', req.body, function(err, resp) {
if (err) return callback(err);
return res.json({success: 'Insert row success'});
});
},
}
// Express routing
app.post('/project/*', crud.newProject);
res.json() by default should add a 200 Success code to the response header. Ideally you would want to inspect the resp data param from the node callback after checking the state of err to properly handle the response and proceed accordingly, especially if you are dealing with last evaluated records associated with a continuation token usually provided in the response which some DBALs and APIs do for you and some don't. Either way you will want to be sure additional recursion isn't necessary to fetch remaining records before responding successfully.
Looks like the res object is undefined as it is not returning any response after the insert. You may return a new object like:
return {
status: 200,
json: {success: 'Insert row success'}
}