Node/Express Redirect After POST - javascript

I have an Express post route which updates a mongo db based on data sent to it from a DataTables Editor inline field. So far so good and the database is updating fine. Where it falls over is after the update query executes successfully and I want to then redirect back to the originating page. The Node console seems to indicate that the GET route to the originating page is being called, but the page itself doesn't load.
The code for the POST function is as follows:
router.post('/edit', function(req,res){
var theKeys = _.keys(req.body);
var theMeat = theKeys[1];
var bits1 = theMeat.split("][");
// this is the updated value
var newVal = req.body[theMeat];
// this is the row _id
var cleanId = bits1[0].replace("data[row_","");
// this is the field to update
var cleanRow = bits1[1].replace("]","");
// cast the id string back to an ObjectId
var updId = new ObjectId(cleanId);
var query = {};
query[cleanRow] = newVal;
var MongoClient = mongodb.MongoClient;
var url = 'mongodb://localhost:27017/gts';
MongoClient.connect(url, function(err, db){
if(err){
console.log("Error connecting to the server", err);
}else{
//console.log("Connected for Edit");
var collection = db.collection('events');
collection.updateOne({"_id":updId},{$set:query},function(err,result){
if(err){
console.log("Error adding message", err);
}else if(result){
//console.log("Update attempted", result.result);
res.redirect('/admin');
}else{
console.log("Unknown error");
}
});
}
});
});
The GET route works fine when called directly, but seems to halt when called like this.
I'm pretty sure that there's nothing in the POST route that is causing this as the same thing happens when I strip out everything except the redirect itself.
router.post('/test',function(req,res){
res.redirect('/admin');
});
Please help!

Related

Conditionally Rendering EJS Template Views to the Same Path

So, very newbie question, but I searched for a couple hours and couldn't find this specific problem (I know I'm doing something dumb).
I am grabbing data from a simple sqlite database table, processing if certain rows are a specific value, pushing them into a table (which I use to push to one of the EJS pages), and then want to render a page based on if there is any data in the table or not.
I want to read the table at a certain interval (using setInterval) and then if there has been a change, update the "view".
All of it has gone decently well, except for when the EJS page actually has to switch from one page to another. I'm not even sure if it's possible to do this, once it's rendered. But, I'd prefer to just render a different page on the same path ('/') that changes on browser refresh.
The initial conditional statement renders the correct EJS page, but like I said, once it needs to switch, the page remains on browser refresh.
I've tried moving the placement of the conditional in multiple places (inside the "get", outside, etc.).
Also tried doing the "if" statement inside a single EJS page, but it just won't refresh once the initial page is rendered and then the function is called again with the setInterval.
var sqlite3 = require('sqlite3').verbose();
var express = require('express');
var app = express();
fs = require('fs')
app.set('view engine', 'ejs');
function query(){
var db = new sqlite3.Database('./my_database.sqlite', sqlite3.OPEN_READWRITE, (err) => {
if (err) {
console.error(err.message);
}
console.log('Connected to the chinook database.');
});
var sql = `SELECT column1 column1
FROM myTable
WHERE column1 = ?`;
var mkts = []
db.each(sql, ['a'], (err, row) => {
if (err) {
throw err;
}
mkts.push(row.column1);
console.log(mkts);
});
db.close((err) => {
if (err) {
return console.error(err.message);
}
console.log('Close the database connection.');
console.log(mkts.length);
if(mkts.length>0){
console.log(true);
app.get('/', function(req, res){
res.render('alert', {mkts:mkts});
});
}else{
console.log(false);
app.get('/', function(req, res){
res.render('index', {mkts:mkts});
});
}
});
};
query();
setInterval(() => query(), 10000);
app.listen(3000);
So basically after opening and then querying the data I want, I'm running the get and render at the db.close. In this code, I can get the "true" and "false" to log appropriately when the DB changes, but the render will not change once the overarching function is run once.
Sorry if its hard to read, but it's been driving me nuts all day.
Your logic (retrieving the datas, view switch) has to be INSIDE your app.get("/"...
Here, you're querying the datas only once (on server) startup and set a static route with static datas.
Try something like this :
// connect to db on startup
var db = new sqlite3.Database('./my_database.sqlite', sqlite3.OPEN_READWRITE, (err) => {
if (err) {
console.error(err.message);
}
console.log('Connected to the chinook database.');
});
// define your routes
app.get('/', function(req, res){
// when route is asked by your browser retrieve the datas
var sql = `SELECT column1 column1
FROM myTable
WHERE column1 = ?`;
var mkts = []
db.each(sql, ['a'], (err, row) => {
if (err) {
throw err;
}
mkts.push(row.column1);
console.log(mkts);
});
// render the good view according to your datas
if(mkts.length>0){
res.render('alert', {mkts:mkts});
}
else {
res.render('index', {mkts:mkts});
}
});
app.listen(3000);
In addition, your setInterval to refresh the view cannot be done here, the "refresh" has to be asked by the client. In your view simply put something like this in javacript :
<script>setTimeout(function(){document.location.reload();}, 1000);</script>

API post request body is empty when entering data in

I am trying to have a simple post function which uses bcrypt on the password passed, then stores the data in the database, however when I call the post request in postman I am getting an error. I add a console output to see what the body was showing up as, and it is just showing an empty object. Does anyone know what could be causing this? Below is my server code:
app.post('/createUser/', function(req, res) {
console.log("below is the req body");
console.log(req.body);
var pass = bcrypt.hashSync(req.body.password, salt);
var createPromise = interact.createUser(req.body.username,
pass,);
//did promise
createPromise.then(function(createResponse) {
if (createResponse.length > 0){
//this means that there was a user with that username in the db
res.json("yes");
}
else {
// otherwise, there wasn't anything in the database with this id
res.json("no");
}
}).catch(function(err) {
console.log(err);
console.log(req.body);
res.status(500).json(err);
});
});

get count collection with socket.io-mongodb

I'm trying to make a simple task.
In the first place, on client side, i'm sending data to server and then i insert these data into my mongodb database.
Then i try to get count of clients from my database.
var express = require('express');
var MONGO_URL = "mongodb://localhost:27017/mydatabase";
var app = express(),
server = require('http').createServer(app),
io = require('socket.io').listen(server),
mongo = require('mongodb').MongoClient,
fs = require('fs');
var countUserSuscribed =0;
//here i insert data
/* Connection events */
io.on('connection', function (client) {
console.log("User connected");
client.on('InsertNewUser', function (newUser) {
console.log("we ar in InsertNewUser event");
//////////////////////////////////////////////////////////
mongo.connect(MONGO_URL, function (err, db) {
console.log("we are connected to mongodb");
var Users = db.collection('User');
console.log("on crée la collection et on fait l'ajout");
Users.insert({ player: myP }, function (err, o) {
if (err) { console.warn(err.message); }
else { console.log("user inserted into db: user"); }
});
});
})
});
//GET COUNT USER
console.log("here we get count user");
mongo.connect(MONGO_URL, function (err, db) {
countUserSuscribed = Users.count();
console.log("we got " + countUserSuscribed + " user in mongoDB");
});
With this code i can create collections and insert documents but the count function doesn't work and i didn't find much explanations on npm documentation.
Is it possible to use others mongodb functions than insert and collection with socket.io-mongodb ?
If it is, can someone give an example or explain me how to use it?
The count function works but is async function and takes a callback.
here's the fix:
countUserSuscribed = Users.count(function (err,c) { console.log(c) });
https://www.npmjs.com/package/mongodb-autoincrement consider using that. It keeps a track of all inserted document. Plus it has a handy feature to get the next count. Example let's say you inserted two records. If you call next count it will show 3. There fore to get the total documents inserted call get next count - 1. Make sense?
Sorry here is the correct one. https://www.npmjs.com/package/mongoose-auto-increment

How to properly use Parse.query.equalTo?

In my web application when the user logs in they should see all the documents they made. However when I test my application, I see all the documents including the ones that I didn't make. I believe this is because I am not using Parse.query.equalTo correctly.
Here is my code:
router.post('/login', function (req, res) {
var tempname = req.body.username;
var username = tempname.toLowerCase();
var password = req.body.password;
var login = Promise.promisify(Parse.User.logIn);
var promerror = Promise.reject("error");
var Files = Parse.Object.extend("File");
var query = new Parse.Query(Files);
query.include('user');
var finds = query.find;
var doc = {};
var name, url;
return login(username, password).catch(function (error) {
}).then(function (user, error) {
query.equalTo("user", Parse.User.current());
console.log(JSON.stringify(Parse.User.current()));
if (user) {
res.render('logins', { Message: "Username and/or password don't match" });
}
var temp;
}).catch(function (err) {
res.render('logins');
}).then(query.find(function (results) {
for (var i = 0; i < results.length; i++) {
var object = results[i];
var userID = object.get('user');
console.log("current user");
var codefile = object.get('javaFile');
temp = codefile.name();
name = temp.split("-").pop();
url = codefile.url();
doc[name] = url;
}
})).catch(function (error) {
promerror(error);
}).finally(function () {
res.render('filename', { title: 'File Name', FIles: JSON.stringify(doc) });
}).done();
});
When the user logs in, it should go to the database retrieve all the documents the user made, and save it to doc, the doc is then send to the client side to be displayed.
here is the code for user saving a file:
newFile.save({ user: Parse.User.current(), fileName: newnames, javaFile: parseFile })
I'm not sure, but try setting the File user field to the object id instead of the user object itself. Parse objects sometimes will return a pointer, sometimes the id, etc. So you might be getting unexpected behavior where you're setting the field to Parse.User.current(). Besides that, you look like you're using equalTo correctly.
Otherwise, basically the only way to debug cloud code is to console.log and view the logs.
As a side note, you should be setting the ACL of each File before you save it... that way, a user wouldn't be able to view another user's files anyway (unless these files are meant to be public).

Nano Couchdb cant get up a folder

I have a database called "visitors" he has the same _ids as another database called "users". I use views so one a user goes to http://localhost:3000/sitename, it uses the data inside _utiles/users/sitename, and it works smooth.
now inside that site I have a form, what I want to do--> the data from the form need to be send to /visitors/sitename/NEW ID/Data, all I manage to do is just open up inside sitename some data, and only for the first time, after that, all gets update conflicts.
I read everything Nano - Couchdb has to offer, cant seem to figure that out.
here is code example:
app.post('/update', function(req, res){
var sitename=req.body.title;
var arrive =req.param('arrive');
var fsname = req.param('fsname');
var number = req.param('number');
var no_arrive_reason = req.param('no_arrive_reason');
update_db = nano.db.use(sitename)
update_db.insert({arrive: arrive, fsname: fsname ,number:number,no_arrive_reason:no_arrive_reason},fsname, function(err, body , header) {
if (!err)
console.log(body);
else{
// console.log(err);
nano.db.create(fsname, function(err, body) { // want to create it inside /visitors/sitename/ -- and it's created just in main db
if (!err) {
console.log('database:'+fsname+'was created');
}
});
}
});
});
thanks a head!

Categories