404 on page refresh of MySQL query with NodeJS - mysql

So i have a website that runs on express with some MySQL queries to load photo albums.
The problem is that when i go to /photo everything works fine but if I refresh the page then i get a 404 NOT FOUND. Same if i go first to /photo then on another url and back to /photo.
The problem happens regardless if it's in prod or dev but only happens on my server, never on local.
here's what i get :
NotFoundError: Not Found
at /home/vincdgfq/sachalebas/app.js:53:7
at Layer.handle [as handle_request] (/home/vincdgfq/nodevenv/sachalebas/9/lib/node_modules/express/lib/router/layer.js:95:5)
at trim_prefix (/home/vincdgfq/nodevenv/sachalebas/9/lib/node_modules/express/lib/router/index.js:317:13)
at /home/vincdgfq/nodevenv/sachalebas/9/lib/node_modules/express/lib/router/index.js:284:7
at Function.process_params (/home/vincdgfq/nodevenv/sachalebas/9/lib/node_modules/express/lib/router/index.js:335:12)
at next (/home/vincdgfq/nodevenv/sachalebas/9/lib/node_modules/express/lib/router/index.js:275:10)
at /home/vincdgfq/nodevenv/sachalebas/9/lib/node_modules/express/lib/router/index.js:635:15
at next (/home/vincdgfq/nodevenv/sachalebas/9/lib/node_modules/express/lib/router/index.js:260:14)
at Function.handle (/home/vincdgfq/nodevenv/sachalebas/9/lib/node_modules/express/lib/router/index.js:174:3)
at router (/home/vincdgfq/nodevenv/sachalebas/9/lib/node_modules/express/lib/router/index.js:47:12)
If i remove all my error handlers i just get a
CANNOT GET /501.shtml
website can be found here : https://sachalebas.com/photo
Thanks in advance if anyone has got any idea where i should look for with this error i'm totally lost.
EDIT:
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var bodyParser = require('body-parser');
var session = require('express-session');
require('./controllers/userController');
const oneYear = 60 * 1000 * 60 * 24 * 7;
const xssFilter = require('x-xss-protection');
const noSniff = require('dont-sniff-mimetype');
require('dotenv').config({ path:"process.env"});
const compression = require('compression');
var indexRouter = require('./routes/index');
var app = express();
app.use(xssFilter());
app.use(noSniff());
app.use(compression());
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
app.use(express.static(__dirname + '/public', {maxAge: oneYear, dotfiles:'allow'}));
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({
extended: false
}));
app.use(cookieParser());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(session({
secret: process.env.SECRET,
resave: false,
saveUninitialized: false,
maxAge: 200000
}));
app.use('/', indexRouter);
// catch 404 and forward to error handler
app.use(function (req, res, next) {
next(createError(404));
});
// error handler
app.use(function (err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
Here's my app.js

Your issue not with backend.
I've done curl requests multiple times and I'm getting same output:
which means issue on clientside with race conditions.
to avoid it try to wrap all code: https://sachalebas.com/ressources/js/script.js
Inside of:
window.onload = function() {
// here goes all js code from ressources/js/script.js
}
or make sure You don't have blocking layer in css that being rendered before image.

Related

Nodejs + express + mysql : Wish to create a customer profile page but end up all the path messed up

I will try to describe my question well and what I trying to archieve
I have lots of table like this in my nodejs app
everying member I will give it a href to "/profile/"theirUsername""
after watching ton of tutorial,
I add a button href to my username
$('#pendingDepositTable').append(`
<tr>
<td>
<div class="d-flex align-items-center">
<div class="table-user-name ml-3">
<p class="mb-0 font-weight-medium">`+ response[i].id + `</p>
</div>
</div>
</td>
<td>
<a href="/profile/`+ response[i].customer + `">
`+ response[i].customer + `
</a>
</td>
<td>`+ response[i].bank + `</td>
<td>`+ response[i].amount + `</td>
<td>
<div class="badge badge-inverse-warning"> `+ response[i].status + ` </div>
</td>
<td>`+ response[i].date + `</td>
<td>
<i class="mdi mdi mdi-check-all"></i>
<i class="mdi mdi-close"></i>
</td>
</tr>
`)
}
I add this in my profile.js
router.get('/:id', function (req, res, next) {
console.log(req.params.id);
db.query("SELECT * FROM `customers` WHERE `username` = '" + req.params.id + "'", function (err, result, field) {
try {
res.render('templateMember', { customers_profile: result });
} catch (error) {
console.log(error)
}
})
Before I render the page, I use res.send(result) and get the data that I want successfully.
But all of my header and js script all messed up (I put these in partials.)
and the url all gone wrong
example my transaction page is http://localhost:3000/deposit
but if i redirect from here it become http://localhost:3000/profile/deposit
What can I do or if i miss something?
my projects folder
my app.js
var createError = require('http-errors');
var express = require('express');
var app = express();
var path = require('path');
var session = require('express-session');
var bodyParser = require('body-parser')
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var mysql = require('mysql');
var flash = require('express-flash');
app.use(flash());
app.use(session({
secret: 'secret',
resave: false,
saveUninitialized: true
}));
var indexRouter = require('./routes/index');
var loginRouter = require('./routes/user_signin');
var memberRouter = require('./routes/members');
var depositRouter = require('./routes/deposit');
var withdrawalRouter = require('./routes/withdrawal');
var creditTransferRouter = require('./routes/creditTransfer');
var cashBonusRouter = require('./routes/cashBonus');
var productListingRouter = require('./routes/products_listing');
var productBalanceRouter = require('./routes/products_balance');
var bankListingRouter = require('./routes/banks_listing');
var bankBalanceRouter = require('./routes/banks_balance');
var bonusRouter = require('./routes/bonus');
var profileRouter = require('./routes/profile')
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
// Login API
app.use('/auth', require('./routes/controllerRoute/auth'));
// Post Product API
app.use('/product_add_action', require('./routes/controllerRoute/product_add_action'));
// Add Member API
app.use('/addMemberRouter', require('./routes/controllerRoute/addMemberRouter'));
app.use('/', indexRouter);
app.use('/userSignin', loginRouter);
app.use('/member', memberRouter);
app.use('/deposit', depositRouter);
app.use('/withdrawal', withdrawalRouter);
app.use('/credittransfer', creditTransferRouter);
app.use('/cashbonus', cashBonusRouter);
app.use('/products_listing', productListingRouter);
app.use('/products_balance', productBalanceRouter);
app.use('/banks_listing', bankListingRouter);
app.use('/banks_balance', bankBalanceRouter);
app.use('/profile', profileRouter);
app.use('/bonus', bonusRouter);
app.all('/', function(req, res){
console.log(req.session)
})
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
Sorry I just found out the answer.
instead of using src="xxx.css"
it should be src="/xxx.css" The leading slash indicates that the request is relative to root not the path that is making the request.
Sorry for post the question without reviewing my code carefully.

trouble in sending data through ajax to express server

I'm new to backend and I was having some trouble in sending data through vanilla ajax to my express server.
please tell me where am I going wrong
my ajax request:
var xhttp = new XMLHttpRequest();
xhttp.onload = function() {
};
xhttp.open("POST", "http://localhost:8080", true);
xhttp.withCredentials = true;
xhttp.send("name=abhishek");
my express server:
var express = require('express');
var cors = require('cors');
var app = express();
app.use(cors({
credentials:true,
origin:'http://127.0.0.1:5500'
}));
var PORT = process.env.PORT || 8080;
const bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
app.get('/', function(req, res){
console.log(req.query);
});
app.listen(PORT, function(err){
if (err) console.log(err);
console.log("Server listening on PORT", PORT);
});
I'm receiving an empty object as the output in my console
There are few things to change.
The client is a POST request but in server side, it is a GET app.get(). Therefore, nothing displayed after request.
Also, Content-type needs to be set to inform server how it is going to parse the message. e.g. JSON/form-data
I assume you want to use POST, below is the change:
Backend:
Change method from app.get to app.post
Get the data from body instead of query
...
app.post("/", function (req, res) {
console.log(req.body); // data is in body instead of query
res.send("hi"); // send back response to frontend
});
...
Frontend:
Set content-type
var xhttp = new XMLHttpRequest();
xhttp.onload = function() {
alert(xhttp.responseText); // should receive hi
};
xhttp.open("POST", "http://localhost:8080", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.withCredentials = true;
xhttp.send("name=abhishek");

Upload file in Expressjs bodyParser

can I just upload some on file with Expressjs with bodyParser.json() middleware? I'm using Expressjs 4.14 and my app.js snipet is like this
require('dotenv').config();
require('./app/models/db');
var express = require('express');
var session = require('express-session');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var app = express();
var socket_io = require("socket.io");
var io = socket_io();
app.io = io;
var mainRouteConfig = require('./app/routes/routes')(io);
// var notifRouteConfig = require('./app/routes/notif')(io);
// view engine setup
app.set('views', path.join(__dirname, 'app', 'views'));
app.set('view engine', 'ejs');
// uncomment after placing your favicon in /public
// app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static(path.join(__dirname, 'public')));
app.use(cookieParser());
app.use(session({ secret: 'super-secret-code'}));
app.use('/', mainRouteConfig);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
// io.on("connection", function(socket){
// console.log( "A user connected" );
// });
module.exports = app;
I think the problem is in app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false })); when want upload some file using multipart/form-data
BodyParser is mainly used for urlencoded enctype.
For multipart I use Formidable and express-formidable.
npm install formidable express-formidable --save
Take a look at docs here
Good luck

Gets Error when adding MySQL information in server.js when creating RESTful API with Express

I was following instructions to build a RESTful API with Express and MySQL(*1)
But when I change
app.listen(port); //excutable, GET returns welcome message
into
orm.initialize(WConfig.config,function(err,models){
...
in the part 2 of(*1), which is adding MySQL information into server.js,
I gets the following on Node.JS command prompt:
TypeError: Cannot read property 'bear' of undefined
Because this is the first attempt in building RESTful API, I'm not sure what to do to fix it. Help please! Any idea is appreciated.
full code of server.js:
// server.js
var util = require('util');
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var Waterline = require('waterline');
var Bear = require('./app/models/bear');
var WConfig = require('./app/config/waterline');
var orm = new Waterline();
orm.loadCollection(Bear);
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
var port = process.env.PORT || 8080;
var router = express.Router();
router.get('/', function(req, res) {
res.json({ message: 'hello! welcome to our api!' });
});
app.use('/api', router);
// express deprecated res.json(obj,status): use res.status(status).json(obj) instead
router.route('/bears')
.post(function(req,res) {
app.models.bear.create(req.body,function(err,model) {
if(err) return res.status(500).json({ err,err });
res.json(model); //res.json(model) , guess: res.status(200).json(model);
console.log(util.inspect(model));
});
});
//gets error if I change it to following
//
orm.initialize(WConfig.config,function(err,models){
if(err) throw err;
app.models = models.collections;
//app.set('models',models.collections);
app.connections = models.connections;
app.listen(port);
console.log('Magic happens on port ' + port);
});
reference:
1.Create Restful API with Express and waterline (in Chinese)
https://segmentfault.com/a/1190000004996659#articleHeader2
2.Build a RESTful API Using Node and Express 4
https://scotch.io/tutorials/build-a-restful-api-using-node-and-express-4

Node MySQL Connection Not Working

I am new to Node an Express, I have this code which simply connects to a MySQL Db...Nothing is happening when I try to 127.0.0.1:9080. I'm doing something wrong but can't figure out what...nothing in the console no errors, tried in chrome, FF, Safari and IE...Any ideas.
var http = require('https');
var express = require('express');
var app = express();
var hbs = require('hbs');
var path = require('path');
var mysql = require('mysql');
app.set('view engine', 'html');
app.engine('html', hbs.__express);
//mysql connect
var connection = mysql.createConnection({
host : 'mysql://root#localhost/mydb2',
user : 'someone',
password : 'secret'
});
app.get('/', function(request, response) {
connection.query('select * from sometable', function(err, rows){
if (err) throw err;
console.log("Test01=" + row[0].toString());
});
app.listen(9080);
});
You need to write something in the response to see it on the browser.
Add this line before console.log() statement.
response.json(rows);