Heroku Cannot GET/ - node.js

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

Related

How to solve this error , module not found?

I'm getting this error , module not found,
Cannot find module 'D:\2022\Full StackProjects\FullStackRegisterLoginPage\server.js'
thank you
Error image
server.js
const express = require("express");
const colors = require("colors");
const dotenv = require("dotenv").config();
const { errorHandler } = require("../Backend/Middleware/errorHandler");
const port = process.env.PORT || 8000;
const app = express();
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use("/api/users", require("./Routes/userRoutes"));
app.use(errorHandler);
app.listen(port, () => {
console.log(`Server is running on port ${port}`);
});
userRoutes.js
const express = require("express");
const router = express.Router();
const {
registerUser,
loginUser,
getUser,
} = require("../Controllers/userController");
router.post("/", registerUser);
router.post("/login", loginUser);
router.get("/me", getUser);
module.exports = router;
errorHandler.js
const errorHandler = (err, req, res, next) => {
const statusCode = res.statusCode ? res.statusCode : 500;
res.status(statusCode);
res.json({
message: err.message,
stack: process.env.NODE_ENV === "production" ? null : err.stack,
});
next();
};
module.exports = { errorHandler };
package.json
package.json
check this out , i've upload all code on github
github repo link

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

How to read a file in node js?

When i want to read a file in node js it won't display the file in the browser when I execute.
and in the terminal says no such file or directory while I use the exact file path anyone can answer this why?
Here is the code:
const express = require('express');
const app = express();
const fs = require('fs');
const bodyParser = require('body-parser');
const CORS = require('cors');
let port = 3000;
app.use(CORS());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false}));
app.use(express.static('Docs'));
app.get('/', (req, res) => {
res.json({name: 'waris', favFood: 'Pizza'})
fs.readFile('./docs/index.html', (err, data) => {
if(err){
console.log(err)
}else{
res.send(data);
}
})
})
app.listen(port, () => {
console.log(`Running on port ${port}`);
})

Change ip Nodejs

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

Cannot GET , nodejs

I tired to solve this problem, when I browse localhost:5000 I got error like
Cannot GET /
//*****************app.js************
const express = require('express');
const mongoose = require('mongoose');
const logger = require('morgan');
const bodyParser = require('body-parser');
const app = express();
const v1 = require('./routes/v1');
// ************* DB Config *************//
mongoose.connect(process.env.MONGO_DB_URL, {
useNewUrlParser: true,
useCreateIndex: true
});
mongoose.connection.on('connected' , () => {
console.log('Connected to the databse');
});
mongoose.connection.on('error' , (err) => {
console.error('Failed to connected to the databse: ${err}');
});
//**************Midlewares ***********//
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended : true}));
//*************Routes *****************//
app.use('/api/v1', v1);
module.exports = app ;
//********** index.js ***************//
require('dotenv').config();
const app = require('./src/app')
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log('Server is ready for connections on port ${PORT}');
});
the problem here is you have no route at the root /
you have to add either your routes you defined or define a root route

Resources