Change ip Nodejs - node.js

I created a mean stack application, I am deploying it in a virtual machine
the problem is that I need to change the localhost(localhost:4200) address to the ip of the machine 10.10.10.15(10.10.10.15:4200) I don't know how to do it
const path = require("path");
const express = require("express")
const mongoose = require("mongoose")
const db = require("./db/db")
const header_middleware = require("./middlewares/header")
const postRouter = require("./Routes/post");
const userRoutes = require("./Routes/user");
const profileRoutes = require("./Routes/profile");
var cors = require('cors');
const app = express()
app.use(cors({origin: '*'}));
const PORT = process.env.PORT || 3000
app.use(express.json())
app.use(header_middleware)
const directory = path.join(__dirname, './images');
app.use("/images", express.static(directory));
// app.use("/", express.static(path.join(__dirname, 'angular')));
app.use("/api/posts", postRouter)
app.use("/api/user", userRoutes);
app.use("/api/profile", profileRoutes);
app.get('/test', (req, res) => {
res.send('Hello World!')
})
app.listen(PORT, (req,res) => {
console.log(`app is listening to PORT ${PORT}`)
})

Instead of using your ip you can use your computer-name:4300 in your browser for example laptop-xxxxx:4300. To find your computer name you can go to about in your settings and it will say the name of your computer. If that doesn’t work check this answer out: https://stackoverflow.com/a/34659560/11365636

Related

Heroku Cannot GET/

I deployed my project with Heroku and everything works correctly but when I refresh the page I received the error "Cannot GET /home". Is there anyone can help me? https://fresh-bio.herokuapp.com/
server.js:
require("dotenv").config();
const express = require("express");
const cors = require("cors");
const app = express();
const connectDB = require("./config/connectDB");
const routesProducts = require("./routes/productsRoutes");
const routesUsers = require("./routes/userRoutes");
app.use(express.json());
app.use(cors());
connectDB();
app.use("/api/products", routesProducts);
app.use("/api/users", routesUsers);
app.use(express.static("client/build"));
app.get("/", function (req, res) {
res.sendFile("client/build/index.html");
});
if (process.env.NODE_ENV === "production") {
app.use(express.static("client/build"));
}
const PORT = process.env.PORT || 5000;
app.listen(process.env.PORT, (err) =>
err
? console.error(err.message)
: console.log(`This server is running on localhost:${process.env.PORT}...`)
);
require("dotenv").config();
const express = require("express");
const cors = require("cors");
const app = express();
const connectDB = require("./config/connectDB");
const routesProducts = require("./routes/productsRoutes");
const routesUsers = require("./routes/userRoutes");
app.use(express.json());
app.use(cors());
connectDB();
app.use("/api/products", routesProducts);
app.use("/api/users", routesUsers);
app.use(express.static(__dirname + "/client/build/"));
app.get(/.*/, (req, res) => {
res.sendFile(__dirname + "/client/build/index.html");
});
const PORT = process.env.PORT || 5000;
app.listen(process.env.PORT, (err) =>
err
? console.error(err.message)
: console.log(`This server is running on localhost:${process.env.PORT}...`)
);

Nodejs is not able to work after creating different routing files

I have an error while running my index.js file after separating the code into different files.
I'm running index.js in the terminal in the right folder as required.
This is my index.js file:
const express = require("express");
const app = express();
const Joi = require("joi");
const genres = require("./routes/genres");
const home = require("./routes/home");
app.use(express.json());
app.use("/api/genres", genres);
app.use("/api/home", home);
const port = process.env.PORT || 3000;
app.listen(port, () => console.log(`you are listening to port ${port}`));
This is my genres file for routing:
const express = require('express');
const router = express.Router();
.
.
.My routing settings
.
.
module.exports = router;
This is the error that I get in vs code after running index.js via terminal:
Will be glad to get any assistance.
index.js
const genres = require("./routes/genres")(app);
const home = require("./routes/home")(app);
app.use("/api/genres", genres);
app.use("/api/home", home);
genre.js
const express = require('express');
const router = express.Router();
router
.get('/', async (req, res) => {
res.send('get data');
})
.post('/add', async (req, res) => {
res.send('get data');
})
module.exports = router;

Postman cannot connecto NodeJS server even if its running?

I wrote this code in my node app
const express = require("express");
const cors = require("cors");
const pool = require("./db");
const app = express();
//middleware
app.use(cors);
//access req.body
app.use(express.json());
app.get("/", async (req, res) => {
try {
res.json("response from server");
// const allCompanies = await pool.query("SELECT * FROM COMPANIES");
// res.json(allCompanies.rows);
} catch (error) {
console.log(error.message);
}
});
const port = 1337;
app.listen(port, () => {
console.log(`Server is starting on port ${port}`);
});
In my terminal it says its running on 1337 however when i try to connect to postman it leaves me hanging? never had this problem before.
const express = require("express");
const cors = require("cors");
const app = express();
app.use(cors());
The problem was that you were not calling the cors function on your app.use middleware.
If you change the code to
app.use(cors());
It should work.
Express Documentation

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}`);
});

Resources