NodeJS reload page but don't send user data again [duplicate] - html

This question already has answers here:
How to prevent form resubmission when page is refreshed (F5 / CTRL+R)
(21 answers)
Closed 4 years ago.
I have a Node Js local server and several identical html pages. On every page I save some user data input fields saved simply on a text file. My problem is that if the users refresh the page the data from the previous html page is send again and again saved on the text file. Is there a way to prevent this?
var fs = require('fs');
const log=require('simple-node-logger').createSimpleLogger();
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
var port = process.env.PORT || 8000;
app.use(express.static(__dirname + '/server'));
app.use(express.static(__dirname + "/public"));
app.use('/images', express.static(__dirname +'/images'));
app.listen(port, function(){
console.log('server is running on ' + port);
});
app.get('/', function(req, res){
res.sendfile('intro.html');
});
app.post('/userID', function(req, res){
//save the userID on a text file
var userID= req.body.userID + ';';
var data = fs.appendFileSync('temporary/userID.txt', userID, 'utf8');
return res.sendfile('main.html');
});
app.post('/submit', function(req, res){
res.sendfile('main2.html');
});
Furthermore, I have also a refresh button that does the same as the browser refresh button. I s there a way to avoid the same problem?
<button>Reset</button>
and its JavaScript:
document.addEventListener('DOMContentLoaded', function () {
document.querySelector('button').addEventListener('click', clickHandler);
});
function clickHandler(element) {
location.reload();
}
Thank you in advance!

You can use fs.readFile and check if that file contain that userId
If that is not present then append or else dont append
fs.readFile('temporary/userID.txt', function (err, fileData) {
if (err) throw err;
if(fileData.indexOf(userID) == -1){
var data = fs.appendFileSync('temporary/userID.txt', userID, 'utf8');
}
});
So, the code will be:
app.post('/userID', function(req, res){
//save the userID on a text file
var userID= req.body.userID + ';';
fs.readFile('temporary/userID.txt', function (err, fileData) {
if (err) throw err;
if(fileData.indexOf(userID) == -1){
var data = fs.appendFileSync('temporary/userID.txt', userID, 'utf8');
}
});
return res.sendfile('main.html');
});

Related

Node/Express + MySQL: Inserts not displaying instantly

I have a form called #add_blog_post with the action "/mysql_test/add_blog_post" and method of "POST"
Jade markup:
form#add_blog_post(action="/mysql_test/add_blog_post" method="POST")
This form executes the following code in my app.js:
app.post('/mysql_test/add_blog_post', function(req, res) {
var author = req.body.author;
var date = req.body.date;
var title = req.body.title;
var body = req.body.body;
var blog_insert_query = "insert into 332project.blog(author,date,title,body) values(";
blog_insert_query += ("'"+author+"'"+","); blog_insert_query += ("'"+date+"'"+","); blog_insert_query += ("'"+title+"'"+","); blog_insert_query += ("'"+body+"'"+")");
var connection = mysql.createConnection({
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASS
});
connection.connect(function(err) { /*error?*/ });
var result;
var query = connection.query(blog_insert_query, function(err, result) {
res.redirect('/mysql_test');
});
});
The blog post insert works just fine but the website takes a while for the insert to be displayed from the select statement on /mysql_test.
Here is my route:
var express = require('express');
var router = express.Router();
var db_calls = require('../db.js');
var connection = db_calls.connect();
connection.connect(function(err) { /*error?*/ });
var result;
var query = connection.query("select * from 332project.blog order by id desc", function(err, rows, fields) {
connection.end();
if (!err) {
result = rows;
}
});
router.get('/', function(req, res, next) {
res.render('mysql_test', {
result: result
});
});
module.exports = router;
What gives? It almost seems like a caching issue. I'd really like for my create/update operations to be instantly visible in my application.
Source code: https://github.com/harwoodjp/learning-express
Your problem is probably that you're not calling connection.end() per the docs.

Return undefined answer from multer

I am using multer in my nodejs application for uploading files. And angularjs for the front end part. Once I click upload image, on the console I am getting undefined answer. Can any one help me to solve the problem.
Here I am pasting the code.
server.js
var express = require('express');
var app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var bodyParser = require('body-parser');
var path = require('path');
var fs = require('fs');
var spawn = require('child_process').spawn;
var multer = require('multer');
var storage = multer.diskStorage({
destination:function(req,file,cb){
cb(null,'public/upload/');
},
filename:function(req,file,cb){
cb(null,file.originalname);
}
});
var upload = multer({storage: storage});
app.set('views', __dirname + '/views');
app.use(bodyParser.json());
var urlencodedParser = bodyParser.urlencoded({ extended: true });
app.use(express.static('public'));
app.get('/',function(req,res){
res.render('index',{ title: 'Upload image' });
});
app.post('/loadImage',upload.any(),function(req, res) {
console.log(req.files);
console.log("Inside post");
});
http.listen(8080,'0.0.0.0',function(){
console.log('listening on 8080');
})
And here is my app.js angularjs code
var app = angular.module('app',['ui.router','ui.bootstrap','ngAnimate']);
$scope.img={};
app.controller('Ctrl',function ($scope,$http){
$scope.loadImage = function(){
$http.post('/loadImage',$scope.img).success(function(data){
console.log('Posted successfully');
}).error(function(data){
console.error('error');
})
};
And my HTML code:
<form ng-submit="loadImage()" enctype="multipart/form-data">
<input type="file" name="file" multiple />
<input type="submit" value="Upload Image" name="submit" />
</form>
On the console I am getting Undefined and Inside post. And on the browser console I am getting posted successfully Can any one please help me to solve this. Instead of undefined I should get loaded file information.
This how i used Multer to upload an image
var multer = require('multer');
exports.loadImage = function (req, res) {
var upload = multer({
inMemory: true,
limits: {fileSize: 1024 * 1024 }
}).single('newPicture');
upload(req, res, function (uploadError) {
if (uploadError) {
return res.status(400).send({ message: 'errorUploadingPicture' });
}
else {
var profileImage = 'No data uploaded';
// this is where the photo data is
if (req.file && req.file.buffer) {
profileImage = req.file.buffer;
}
return res.json(profileImage );
}
});
};
This is all assuming you are sending your file correct
try
var uploadType = upload.any()
and change
app.post('/loadImage',upload.any(),function(req, res) {
console.log(req.files);
console.log("Inside post");
});
to
app.post('/loadImage',uploadType,function(req, res) {
console.log(req.files);
console.log("Inside post");
});
if you are attempting to only get one file at a time then instead,
var uploadType = upload.single('file')
app.post('/loadImage',uploadType,function(req, res) {
console.log(req.files);
console.log("Inside post");
});

how do we pass the parameters to db via url in express js?

I'm trying to insert the value to db through html page & passing the value to url. But value has been inserted as null merely inserting the value from html page it's working but through url null value has been inserted.
var express=require('express');
var app=express();
var sql=require('mysql');
var createConnect=sql.createPool({
host:"localhost",
user:"root",
password:"",
database:"stud"
});
app.get('/',function(req,res){
createConnect.getConnection(function(err,row){
if(err) throw err;
res.send("connected");
console.log("connected");
});
});
app.use(express.static('public'));
app.get('/index.html', function(req,res){
res.sendFile(__dirname+"/"+"index.html");
});
app.get('/process1/:fname/:rno/:MobNO',function(req,res){
If I remove the data1 value is inserted to db but I want to inset the data through url and html page also.
var data1={
sname:req.params.fname,
regno:req.params.rno,
mobno:req.params.MobNo
};
var data={
sname:req.query.fname,
regno:req.query.rno,
mobno:req.query.MobNo
};
createConnect.query("INSERT INTO student set?",(data1,data), function(err,rows){
if(err) {
console.log("check your query",err);
}
res.send("hello ram");
});
});

How to connect static HTML and CSS files to Node.js application?

I try to show a (static) HTML webpage via Heroku. I have followed this tutorial: https://www.youtube.com/watch?v=gAwH1kSODVQ but after many attempts it is still not working.
I'm rather new to coding, so if you can give concrete examples that would be great!
The following files have been pushed to heroku:
server.js
package.json
Procfile.js
(folder) public with index.html, main.css
//Server.js file:
var express = require('express'); //require express module in server.js file
var app = express();
var mongojs = require('mongojs');
var db = mongojs('birthdaylist', ['birthdaylist']);
var bodyParser = require('body-parser');
var http = require('http');
var port = Number(process.env.PORT || 3000);
app.use(express.static(__dirname + '/public')); //connect to html file
app.use(bodyParser.json());
app.get('/birthdaylist', function(req, res) {
console.log("The server has received a GET request.")
db.birthdaylist.find(function(err, docs){
console.log(docs);
res.json(docs);
});
});
app.post('/birthdaylist', function(req, res){
console.log(req.body);
db.birthdaylist.insert(req.body, function (err, doc){
res.json(doc);
});
});
app.delete('/birthdaylist/:id', function(req, res){
var id = req.params.id;
console.log(id);
db.birthdaylist.remove({_id: mongojs.ObjectId(id)}, function(err, doc){
res.json(doc);
});
});
app.listen(port, function () {
});
you should use:
app.listen(%PORT_NUMBER%, function () {
// some code here
});
Instead of:
var server = http.createServer(function(req, res){
res.writeHead(200, {'Content-Type':'text/html'});
res.end('<h6>Hello worldsfasfd!</h6>');
});

node.js data fetch in json model error

I am new to node.js
I was just making an simple application
my data is inserting properly into the database as well as fetching also from the database
But the problem is when I am trying to access it in json model it is giving me error
var express = require('express');
/*
* body-parser is a piece of express middleware that
* reads a form's input and stores it as a javascript
* object accessible through `req.body`
*
* 'body-parser' must be installed (via `npm install --save body-parser`)
* For more info see: https://github.com/expressjs/body-parser
*/
var bodyParser = require('body-parser');
// create our app
var app = express();
// instruct the app to use the `bodyParser()` middleware for all routes
app.use(bodyParser.urlencoded({ extended: true }));
// A browser's default method is 'GET', so this
// is the route that express uses when we visit
// our site initially.
app.get('/', function(req, res){
// The form's action is '/' and its method is 'POST',
// so the `app.post('/', ...` route will receive the
// result of our form
var html = '<form action="/" method="post">' +
'Enter your name:' +
'<input type="text" name="userName" placeholder="Put your name" />' +
'<br>' +'Enter your city:'+'<input type="text" name="userCity" placeholder="Put your city" />' +
'<br>' +'Enter your state:'+'<input type="text" name="userState" placeholder="Put your state" />' +
'<br>' +'Enter your country:'+'<input type="text" name="userCountry" placeholder="Put your country" />' +
'<br>' +
'<button type="submit">Submit</button>' +
'</form>';
res.send(html);
});
// This route receives the posted form.
// As explained above, usage of 'body-parser' means
// that `req.body` will be filled in with the form elements
app.post('/', function(req, res){
var userName = req.body.userName;
var userCity = req.body.userCity;
var userState = req.body.userState;
var userCountry = req.body.userCountry;
// var document = {userName:userName,userCity:userCity,userState:userState,userCountry:userCountry};
var html = 'Hello: ' + userName + '.<br>' +'City: ' + userCity + '.<br>'+'State: ' + userState + '.<br>'+'country: ' + userCountry + '.<br>'+
'Try again.';
// res.send(html);
//res.send(JSON.stringify(doc));
//lets require/import the mongodb native drivers.
var mongodb = require('mongodb');
var assert = require('assert');
var ObjectId = require('mongodb').ObjectID;
//We need to work with "MongoClient" interface in order to connect to a mongodb server.
var MongoClient = require('mongodb').MongoClient;
// Connection URL. This is where your mongodb server is running.
var url = 'mongodb://localhost:27017/test';
// Use connect method to connect to the Server
MongoClient.connect(url, function (err, db) {
if (err) {
console.log('Unable to connect to the mongoDB server. Error:', err);
} else {
//HURRAY!! We are connected. :)
console.log('Connection established to', url);
/* var userName = req.body.userName;
var userCity = req.body.userCity;
var userState = req.body.userState;
var userCountry = req.body.userCountry;
var document = {userName:userName, userCity:userCity,userState:userState,userCountry:userCountry};*/
// do some work here with the database.
var insertDocument = function(db, callback) {
db.collection('test').insertOne( {
"userName" :userName,
"userCity" : userCity,
"userState" : userState,
"userCountry" :userCountry ,
}, function(err, result) {
assert.equal(err, null);
console.log("Inserted a document into the test collection.");
callback(result);
});
};
var findDocument = function(db, callback) {
var cursor =db.collection('test').find( );
cursor.each(function(err, doc) {
assert.equal(err, null);
if (doc != null) {
console.log(doc);
// res.contentType('application/json');
res.send(JSON.stringify(doc));
/* app.get('/test', function(req, res, next) {
res.json(doc);
});*/
} else {
callback();
}
// res.send(JSON.stringify(doc));
});
};
MongoClient.connect(url, function(err, db) {
assert.equal(null, err);
insertDocument(db, function() {
findDocument(db, function() {
db.close();
});
});
});
/* var document = {name:"David", title:"About MongoDB"};
db.collection('test').insertOne(document, function(err, records) {
if (err) throw err;
console.log("Record added as "+records[0]._id);
});*/
//Close connection
// db.close();
}
});
});
app.listen(3000);
Please help me to get rid off the problem.
Thank you..
The error I am getting is cann't set headers after they are send
This kind of error usually means that you try using res.send(...) multiple times from the same route.
Here you can see that in your find document, you use a cursor.each, and send your result inside this cursor.each. This means that you send multiple results from the same route.
What you should do instead is having a variable that you use to store your result before sending it once everything is retrieved.