App.use Express not working on heroku - json

I want to deploy my node.js web app on heroku.
My server.js is as follow :
// set variables for environment
var express = require('express');
var bodyParser = require('body-parser')
var app = express();
var pdf = require('express-pdf');
var projectDir = __dirname+'/../..';
app.set('port', (process.env.PORT || 5000));
app.use(express.static(projectDir+'/public'));
app.use(bodyParser.json());
app.use(pdf)
app.use('/pdf', express.static(projectDir + '/data/json/output.pdf'));
app.use('/json', express.static(projectDir+'/data/json'));
require('./saveLastConf')(app, projectDir+'/data/json')
// Set server port
app.listen(app.get('port'), function() {
console.log('Node app is running on port', app.get('port'));
});
console.log('server is running');
My code is working locally but when i try heroku local web or when i deploy it on the website my files under data/json/test.json cannot be found (404)
(i call my file like that : https://a.com/json/test.json )
can anyone help me solve this ?
thank you.

Related

.JS Not running on VS Code

const express = require("express");
const app = express();
app.get("/hello", (req, res) => {
res.send("Hello World");
});
app.listen(3000);
I run this simple code in VS code but It isn't showing in localhost 8080 on web browser
I want to know what did happen and How to solve this one ?

Can feathers co exist with routs managed out side of feathers

We have a large app which uses express for rest and primus for socket routes. It would be very hard to convert all to feathers at once. I am thinking of phased approach where I could take some routes and convert them to services and of cause any new routes will follow the service pattern. I will slowly migrate the rest of the app.
The client is using primus and angularjs $http for now to communicate with nodejs.
our current set up looks like
var http = require('http');
var express = require('express');
var bodyParser = require('body-parser');
var cookieParser = require('cookie-parser');
const csrf = require('csurf');
var Primus = require('primus');
var SocketService = require('./../services/socket-service'); ////this handles existing socket routes from primus client using spark.write
var routesUtils = require('../utilities/routes-utility');
var _ = require('lodash');
module.exports = function(isClusteredDeploy) {
var app = express();
var server = http.createServer(app);
var primus = new Primus(server, {transformer: 'uws'});
var socketService = SocketService(primus);
var commonSocketRoute, commonRoute;
//primus.library();
//primus.save(__dirname + '/primus-client.js');
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(bodyParser.json({
strict: false,
limit: '1mb'
}));
app.use(cookieParser());
app.use(csrf({ cookie: true }));
app.use(function (err, req, res, next) {
if (err.code !== 'EBADCSRFTOKEN') {
return next(err);
}
res.status(403);
res.send();
});
app.use(function(req, res, next) {
res.cookie('XSRF-TOKEN', req.csrfToken());
next();
});
server.listen(config.get(constants.CONFIG_App_Port), function() {
log.info('App server ==> %s is listening on port %d', config.get('rest_host_config.' + config.get('app_key') + '.host'),
config.get(constants.CONFIG_App_Port));
});
//dynamically loading rest routes and socket routes from the file system
var files = routesUtils.readRoutes(true);
files.forEach(function(file) {
if (_.includes(file, 'socket')) {
commonSocketRoute = require('./../../' + file);
commonSocketRoute(socketService);
} else {
commonRoute = require('./../../' + file);
commonRoute(app);
}
});
};
I'd like to add feathers in this and then slowly start converting. Is this possible?
Yes, with the standard #feathersjs/express framework integration your Feathers application will also be a fully Express compatible application which additionally allows to register services.
In your case you would replace var app = express(); with:
const feathers = require('#feathersjs/feathers');
const express = require('#feathersjs/express');
// Create an app that is a Feathers AND Express application
const app = express(feathers());
// Set up REST services (optional)
app.configure(express.rest());
And everything should continue to work as normal. The next step would be to replace the custom Primus code with the #feathersjs/primus framework adapter:
const feathers = require('#feathersjs/feathers');
const express = require('#feathersjs/express');
const primus = require('#feathersjs/primus');
// Create an app that is a Feathers AND Express application
const app = express(feathers());
// Set up Primus with SockJS
app.configure(primus({ transformer: 'ws' }));
Now you can also replace the http.createServer setup with a more simple
const server = app.listen(config.get(constants.CONFIG_App_Port))
Since Feathers will handle all the Express and Primus initialization. The Primus instance will be available as app.primus.

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 JS Configuration

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

app crash in appfog using node js mysql

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