I have an app hosted in appfog using node-express and mysql( and backbone js in the client side), it works fine in localhost but when deploy the app works fine for a moment and after a time crash( if i restart in the console of appfog admin the same thing happens)
this is part of code for connection mysql
var mysql = require("mysql")
var env = JSON.parse(process.env.VCAP_SERVICES);
var creds = env['mysql-5.1'][0]['credentials'];
console.log(creds)
var client = mysql.createConnection({
host: creds.host || "localhost",
user: creds.user,
password: creds.password,
port: creds.port,
database: "savelinks"
});
The code in app.js
var express = require("express");
var path = require("path");
var port = 9000;
var request = require('request');
var cheerio = require('cheerio');
var app = module.exports = express();
console.log(process.env.VCAP_SERVICES)
app.configure(function(){
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
});
var server = require("http").createServer(app)
app.get("/", function(req,res){
res.render("index");
});
/*
* GET ALL LINKS ON LOAD PAGE
*/
app.get("/links", function(req, res){
links = db.client.query("SELECT * FROM links ORDER BY created DESC", function(err, result){
if(!err){
res.json(result)
}
});
});
// more routers
app.listen(process.env.VCAP_APP_PORT || port, function(){
console.log("server run in port " + port)
});
This is the log that app fog shows
events.js:71
throw arguments[1]; // Unhandled 'error' event
^
Error: Connection lost: The server closed the connection.
at Protocol.end (/mnt/var/vcap.local/dea/apps/savelinks-0-ca19c96d36d4701debe7fe46752707c5/app/node_modules/mysql/lib/protocol/Protocol.js:73:13)
at Socket.onend (stream.js:66:10)
at Socket.EventEmitter.emit (events.js:126:20)
at TCP.onread (net.js:417:51)
Any idea for solve this problem?
I had the same kind of issue in production, but not on my personal development machine. My node server uses node-mysql with connect on an Ubuntu VM. My node server would crash and restart now and then throughout the day with the same kind of error you are seeing.
The following approach explained on the node-mysql GitHub page worked to solve the problem for me:
https://github.com/felixge/node-mysql#server-disconnects
Related
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.
Error: Failed to lookup view "app/rooms" in views directory "E:\Angular\project1\views"
at Function.render (E:\Angular\project1\node_modules\express\lib\application.js:580:17)
at ServerResponse.render (E:\Angular\project1\node_modules\express\lib\response.js:1012:7)
at Query.<anonymous> (E:\Angular\project1\server.js:30:13)
at Query.<anonymous> (E:\Angular\project1\node_modules\mysql\lib\Connection.js:525:10)
at Query._callback (E:\Angular\project1\node_modules\mysql\lib\Connection.js:491:16)
at Query.Sequence.end (E:\Angular\project1\node_modules\mysql\lib\protocol\sequences\Sequence.js:83:24)
at Query._handleFinalResultPacket (E:\Angular\project1\node_modules\mysql\lib\protocol\sequences\Query.js:139:8)
at Query.EofPacket (E:\Angular\project1\node_modules\mysql\lib\protocol\sequences\Query.js:123:8)
at Protocol._parsePacket (E:\Angular\project1\node_modules\mysql\lib\protocol\Protocol.js:291:23)
at Parser._parsePacket (E:\Angular\project1\node_modules\mysql\lib\protocol\Parser.js:433:10)
In the directory i don't have folder like "views" there is only src file and other json,node files. If anyone know a better way to connect to server please tell me(Any references)
---------------------THIS IS THE CODE USED FOR SERVER CONNECTION--------------
var express = require('express');
var http = require('http');
var mysql = require('mysql');
var app = express();
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({extended: true}));
app.set('view engine','html');
app.use('/js',express.static(__dirname + '/node_modules/bootstrap/dist/js'));
app.use('/js',express.static(__dirname + '/node_modules/tether/dist/js'));
app.use('/js',express.static(__dirname + '/node_modules/jquery/dist'));
app.use('/css',express.static(__dirname + '/node_modules/bootstrap/dist/css'));
app.engine('html', require('ejs').renderFile);
const con = mysql.createConnection({
host: "localhost",
user: "root",
password: "",
database: "mydb"
});
app.get('/',function(req, res){
con.query("SELECT * FROM rooms ",function (err,result){
res.render('app/rooms',{
pageTitle: "Rooms List",
items: result
});
});
});
var server = app.listen(4200,function(){
console.log("Server started on 4200.....");
})
From what I can see here you are already setting a view engine to render your view from the server. But you said you are using Angular. So you don't need view engine set up.
These two codes should be deleted. Except you are doing server rendering, whereby you want to use what to render your page from the server if so you will need a view folder.
app.set('view engine','html');
app.engine('html', require('ejs').renderFile);
But if you are not doing anything like server rendering just delete those code relating to view.
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
I am trying configure my node js to run my html code.I am using bootstrap and Express Js also.When I run node js its not loading the css.Can anyone help me what could be the issue.Here is the node js code snippet.
var express = require("express");
var app = express();
var path = require("path");
app.get('/',function(req,res) {
res.sendFile(__dirname + '/home.html')
})
app.use(express.static(__dirname + '/public'))
app.listen(3000);
console.log("Running at Port 3000");
When I directly load the HTML files it loads the CSS properly but when i use node js to load it it fails.What could be the cause of the issue?
Check your directory structure is correct and that you have given the correct permission for Node.js to enter the directories and read the file.
If your directory structure looks like this:
/public
/stylesheets
home.css
home.html
server.js
And your server.js code looks like this:
var express = require("express");
var app = express();
var path = require("path");
app.get('/',function(req,res) {
res.sendFile(__dirname + '/home.html');
})
app.use(express.static(__dirname + '/public'));
app.listen('3000', function() {
console.log("Listening on port 3000");
});
When you run this:
node ./server.js
And visit this URL in your browser:
http://localhost:3000/stylesheets/home.css
You will get your home.css file returned.
In express js project to configuration database
/config
/database.js
/server.js
/.env
const http = require('http');
const app = require('express')();
require('./config/database.js');
const bodyParser = require('body-parser');
const server = http.createServer(app);
server.listen(process.env.ServerPort, '0.0.0.0', () => {
logger.info(`Express server listening on port ${process.env.ServerPort}`);
});
When you run this:
node server.js
database.js file
const My = require('jm-ez-mysql');
// Init DB Connection
const connection = My.init({
host: process.env.DBHOST,
user: process.env.DBUSER,
password: process.env.DBPASSWORD,
database: process.env.DATABASE,
dateStrings: true,
charset: 'utf8mb4',
timezone: 'utc',
multipleStatements: true,
connectTimeout: 100 * 60 * 1000,
acquireTimeout: 100 * 60 * 1000,
timeout: 100 * 60 * 1000,
});
module.exports = {
connection,
};
In express js project, as require you can place you static file.
app.use('/static', express.static('public'))
Now, you can load the files that are in the public directory from the /static path prefix.
http://localhost:3000/static/images/kitten.jpg
http://localhost:3000/static/css/style.css
http://localhost:3000/static/js/app.js
http://localhost:3000/static/images/bg.png
http://localhost:3000/static/hello.html
https://expressjs.com/en/starter/static-files.html
check this link for how you can connect your static files with express js
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);