my app have a problem after i refresh the page - node.js

when i open my app for the first time it work just fine but when i refresh the page it give me a url to my index.html file ( /client/build/index.html ) , i have deploy it on heroku
that is the code in my app.js file that create the server
const express = require('express');
const app = express();
const path = require('path');
// create a server for socket io
const http = require('http');
const socketio = require('socket.io');
const server = http.createServer(app);
module.exports = io = socketio(server);
// my middle ware
const morgan = require('morgan');
const bodyParser = require('body-parser');
// Init Middelware
app.use(express.json({ extended: false }));
// my router
const postRoute = require('./nodeapi/routers/post');
const authRouter = require('./nodeapi/routers/auth');
const usersRouter = require('./nodeapi/routers/users');
const friendRouter = require('./nodeapi/routers/friend');
const chatRouter = require('./nodeapi/routers/chats');
const mongoDB = require('./nodeapi/mongodb-database/db');
const port = process.env.PORT;
// Connect monogo database
mongoDB();
// Middel ware
app.use(morgan('dev'));
app.use(bodyParser.json());
// Get the routes
app.use('/', postRoute);
app.use('/', authRouter);
app.use('/', usersRouter);
app.use('/', friendRouter);
app.use('/', chatRouter);
app.use('/file/', express.static('./uploads/'));
// connect to socket io
io.on('connection', (socket) => {});
//Serve static assets in productio
if (process.env.NODE_ENV === 'production') {
// Set static folder
app.use(express.static('./client/build'));
app.get('*', (req, res) => {
res.send(path.resolve(__dirname, '..', 'client', 'build', 'index.html'));
});
}
// listen to the port
server.listen(port, () => {
console.log(`this is port ${port}`);
});
this is when i open it for the first time
this is when i refresh the page

You just need to send it as file not a text
app.use(express.static('./client/build'));
app.get('*', (req, res) => {
res.sendFile(path.resolve(__dirname, '..', 'client', 'build', 'index.html'));
});

Related

Why is my heroku app loading resources too long even after using gzip compression?

I have a MEAN stack app hosted in Heroku. In my Express server, I use gzip (via compression middleware).
const express = require('express');
const path = require('path');
const bodyParser = require('body-parser');
const cors = require('cors');
const passport = require('passport');
const adminpassport = require('passport');
const mongoose = require('mongoose');
const config = require('./config/database');
// Connect to DB
mongoose.connect(config.database);
mongoose.connection.on('connected',()=>{
console.log('Connected to database '+config.database);
});
mongoose.connection.on('error',(err)=>{
console.log('DB Error '+err);
});
const compression = require('compression');
const app = express();
// Static Folder
app.use(express.static(path.join(__dirname, 'public')));
app.use(compression());
// Body Parser Middleware
app.use(bodyParser.json());
...
app.use(function(req, res) {
res.sendFile(path.join(__dirname, '/public', 'index.html'));
});
// Index Route
app.get('/', (req, res)=>{
res.send('Invalid enpoint');
});
app.listen(port, ()=>{
console.log("Server started on port "+port);
});
The problem is that the Angular main.js file (that is orginally 3.2mb, compressed to 575kb) is still seemingly being download as if it's still the uncompressed size. Here's an image of the load times:
I know my internet connection is fine (around 20mbps). Is there anything I'm missing? Is there something wrong in my implementation of gzip? Or even my Heroku dyno? This app is currently on the hobby dyno. I did change it to the professional one but didnt notice any difference.
I'm not sure what is your environment, but you can try this, is completely functional for me.
// Get dependencies
const express = require('express');
const path = require('path');
const http = require('http');
const bodyParser = require('body-parser');
const compression = require('compression');
const runApp = async() => {
const app = express();
app.use(compression({
filter: function (req, res) {
return (/json|text|javascript|css|font|svg/).test(res.getHeader('Content-Type'));
},
level: 9
}));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static(path.join(__dirname, 'public')));
app.get('*', (req, res) => {
console.log('Front end called');
res.sendFile(path.join(__dirname, 'public/index.html'));
});
/**
* Get port from environment and store in Express.
*/
const port = process.env.PORT || '8081';
app.set('port', port);
/**
* Create HTTP server.
*/
const server = http.createServer(app);
/**
* Listen on provided port, on all network interfaces.
*/
server.listen(port, () => console.log(`API running on localhost:${port}`));
};
runApp();

Error while deploying react js and node app to aws

I want to deploy my app to aws, i search and i found alot of tutorials i try each one and i get this error on the browser:
Cannot GET /
I figure maybe that my problem is from my nodeJS server code.
This is my server.js code hope you guys can help me thanks.
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const passport = require('passport');
const path = require('path');
const cors = require('cors');
//Api routes
const users = require('./routes/api/usuario');
const alumno = require('./routes/api/alumno');
const personal = require('./routes/api/personal');
const zonas = require('./routes/api/zonas');
const sepomex = require('./routes/api/sepomex');
const app = express();
app.use(cors());
//Body parser middleware
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
//Db config
const db = process.env.NODE_ENV === "production" ? require('./config/keys').mongoURIProd : require('./config/keys').mongoURIDev;
//connect to mongo DB
mongoose
.connect(db, { useNewUrlParser: true })
.then(() => console.log('MongoDB Connected'))
.catch(err => console.log(err));
//passport middleware
app.use(passport.initialize());
//passport config
require('./config/passport')(passport);
//Use routes
app.use('/api/usuario', users);
app.use('/api/alumno', alumno);
app.use('/api/personal', personal);
app.use('/api/zonas', zonas);
app.use('/api/sepomex', sepomex);
//serve static assets to production
if (process.env.NODE_ENV === "production") {
//static folder
app.use(express.static("client/build"));
app.get('/*', (req, res) => {
res.sendFile(path.resolve(__dirname, 'client', 'build', 'index.html'));
})
}
const port = process.env.PORT || 5000;
app.listen(port, () => {
console.log(`Server running on port ${port}`);
});
I have deployed my app on heroku and works fine.
If you are deploying to EC2 instance then you need to specify IP address in app.listen to be 0.0.0.0, by default it is set to localhost which is not what you want if you want the app to be reachable from outside.
You should change your code to
app.listen(port, '0.0.0.0', () => {
console.log(`Server running on port ${port}`);
});

Cannot configure Router in Express NodeJS

I have the next server file:
'use strict'
const app = require('express')();
const server = require('http').Server(app);
const io = require('socket.io')(server);
const index = require('./routes/index');
const chat = require('./routes/chat');
app.use('/', index);
app.use('/chat', chat);
const port = process.env.API_PORT || 8989;
server.listen(port, () => {
console.log(`Server running on port ${port}`);
});
and the next two routes index.js and chat.js in ./routes dir:
// ./routes/index.js
const express = require('express');
const router = express.Router();
router.route('/')
.get((req, res) => {
res.json('Hello on the Homepage!');
});
module.exports = router;
// ./routes/chat.js
const express = require('express');
const router = express.Router();
router.route('/chat')
.get((req, res) => {
res.json('Hello on the Chatpage!');
});
module.exports = router;
The first one index.js loads normaly by standart port localhost:8989/, but when I what to get the second route by localhost:8989/chat - I always receive error - Cannot GET /chat...
What is I'm doing wrong?
In server.js
const index = require('./routes/index');
const chat = require('./routes/chat');
app.use('/chat', chat); // when path is :/chat/bla/foo
app.use('/', index);
In ./routes/index.js
router.route('/')
.get((req, res) => {
res.json('Hello on the Homepage!');
});
In ./routes/chat.js
// It is already in `:/chat`. There we need to map rest part of URL.
router.route('/')
.get((req, res) => {
res.json('Hello on the Chatpage!');
});
// ./routes/chat.js
const express = require('express');
const router = express.Router();
router.route('/')
.get((req, res) => {
res.json('Hello on the Chatpage!');
});
module.exports = router;
you can use this

express route unable to get

I have a route file for the admin and home pages separately. I also have difference layout files for home and admin. When I access the home and admin routes on my local dev everything is ok, but when I try to access the admin route useing site.com/admin I get Cannot GET /admin/ response. following is my server.js:
const express = require('express');
const exphbs = require('express-handlebars');
const methodOverride = require('method-override');
const flash = require('connect-flash');
const session = require('express-session');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const path = require('path');
const app = express();
// Use path
app.use(express.static(path.join(__dirname, 'public')));
// Map Global Promise
mongoose.Promise = global.Promise;
// Connect to mongoose
mongoose.connect('mongodb://localhost/skillbuild')
.then(() => console.log('MongoDB Connected...'))
.catch(err => console.log(err));
// Load Idea model
// require('./models/Idea');
// const Idea = mongoose.model('ideas');
// Express Handlebars middleware
app.engine('handlebars', exphbs({
defaultLayout: 'main'
}));
app.set('view engine', 'handlebars');
// BodyParser middleware
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
// Method Override middleware
app.use(methodOverride('_method'));
// Load routes
const home = require('./routes/home');
const admin = require('./routes/admin');
// Use routes
app.use('/', home);
app.use('/admin', admin);
// Express session middleware
app.use(session({
secret: 'keyboard cat',
resave: true,
saveUninitialized: true
}));
app.use(flash());
// Global variables
app.use(function (req, res, next) {
res.locals.success_msg = req.flash('success_msg');
res.locals.error_msg = req.flash('error_msg');
res.locals.error = req.flash('error');
next();
});
const port = 80;
app.listen(port, () => {
console.log(`Server started on port ${port}`);
});
my home routes which are in home.js routes file:
const express = require('express');
const router = express.Router();
router.all('/*', (req, res, next) => {
req.app.locals.layout = 'main';
next();
});
// index route
router.get('/', (req, res) => {
res.render('index');
});
// About route
router.get('/about', (req, res) => {
res.render('about');
});
//login route temp
router.get('/login', (req, res) => {
res.render('users/login');
});
module.exports = router;
my admin.js routes file:
const express = require('express');
const router = express.Router();
router.all('/*', (req, res, next) => {
req.app.locals.layout = 'admin';
next();
});
// admin index route
router.get('/', (req, res) => {
res.render('admin/index');
});
module.exports = router;
OK...so the problem simply was that I needed to restart the server with pm2 restart id of the node app in order to load the updated code. Problem solved.

node Cannot POST /api/register

I'm not sure why I am getting the cannot POST error. I am passing the correct routes. The server is listening on a port.
index.js
const router = require('./router');
var app = express()
app.use(express.static(__dirname + "/public"));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
var server = app.listen(process.env.PORT || 8080, function() {
var port = server.address().port;
console.log("App now running on port", port);
});
router(app);
router.js
const Authentication = require('./authentication');
const express = require('express');
const passport = require('passport');
const requireAuth = passport.authenticate('jwt', { session: false });
const requireLogin = passport.authenticate('local', { session: false });
module.exports = function(app) {
const apiRoutes = express.Router();
const authRoutes = express.Router();
apiRoutes.use('/auth', authRoutes);
authRoutes.post('/login', requireLogin, Authentication.login);
authRoutes.post('/register', Authentication.register);
app.use('/api', apiRoutes);
};
You're trying to access /api/register, but look at the way you've registered your routers:
apiRoutes.use('/auth', authRoutes);
authRoutes.post('/login', requireLogin, Authentication.login);
authRoutes.post('/register', Authentication.register);
app.use('/api', apiRoutes);
You've made authRoutes a child of apiRoutes, so /register is being served at api/auth/register.
Easy mistake to make when you've got several routers all linked up to each other :)

Resources