How to solve this error , module not found? - node.js

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

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

Error - Can not see text in visual code when doing a request

I have a simple basic node.js entry file by the name of index.js and the below code for this file is as following:
const express = require("express");
const expressApp = require("./express-app/test.js");
const { PORT } = require("./config");
const { databaseConnection } = require("./database");
const StartServer = async () => {
const app = express();
//database connection
await databaseConnection();
expressApp(app);
app
.listen(PORT, () => console.log(`Customer is listening on port ${PORT}`))
.on("error", (err) => {
console.log(err);
process.exit();
});
};
StartServer();
and also have a file by the name of test.js with the following code as below:
const express = require("express");
const cors = require("cors");
module.exports = (app) => {
app.use(express.json({ limit: "1mb" }));
app.use(express.urlencoded({ extended: true, limit: "1mb" }));
app.use(cors);
app.use(express.static(__dirname + "/public"));
// Listen to Events //
app.use("/app-events", (req, res, next) => {
console.log("Had reached");
});
};
When I do a request with url http://localhost:portnumber/app-events, I can not see "Had reached" in the console.
I'm wondering what am I doing wrong??
I think it should be app.get(...) instead of app.use(..)

Postman keeps loading on sending POST request to an express route

I created a route and controller for my sign up.
Here's my route:
const express = require("express");
const router = express.Router();
const { signup } = require("../../controllers/auth");
router.post("/signup", signup);
module.exports = router;
And here's my controller:
exports.signup = () => (req, res) => {
const { name, email, password } = req.body;
res.json({
user: { name, email, password },
});
};
Inside my server.js file I register both:
const express = require("express");
const morgan = require("morgan");
const cookieParser = require("cookie-parser");
const cors = require("cors");
const mongoose = require("mongoose");
require("dotenv").config();
// routes
const blogRoutes = require("./routes/blog");
const authRoutes = require("./routes/auth");
// app
const app = express();
// db
mongoose
.connect(process.env.DATABASE, { useNewUrlParser: true, useUnifiedTopology: true })
.then(() => console.log("DB connected!"));
// middlewares
app.use(morgan("dev"));
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
app.use(cookieParser());
// cors
if (process.env.NODE_ENV == "development") {
app.use(cors({ origin: `${process.env.CLIENT_URL}` }));
}
// routes middleware
app.use("/api", blogRoutes);
app.use("/api", authRoutes);
// port
const port = process.env.PORT || 8000;
app.listen(port, () => {
console.log(`Server is running on port ${port}`);
});
Now on my POSTMAN, I tried to put the data using POST http://localhost:8000/api/signup with the header and raw setup right.
{
"name": "SyRyan",
"email": "syryan#gmail.com",
"password": "brace1010"
}
The database is connected but the postman takes forever to load the json request back. Am I making any mistakes here? Please help!
I think that the problem is that signup is a function that returns a function, but it should be just a function that receives req & res as parameters:
exports.signup = (req, res) => {
const { name, email, password } = req.body;
res.json({
user: { name, email, password },
});
};

Postman only showing error message and no request is working

Hi so I'm new in this domain and I'm working on some big project so here's the issue, i'm trying to run postman changing the requests from get to post etc but it's not working here's the app.js file
const express = require('express')
const cors = require("cors");
require("dotenv").config();
const con= require("./helpers/connection");
const bodyParser = require('body-parser');
const app = express()
const port = 3000
app.use(cors({ origin: '*' }));
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
// parse env variables
app.use(function(req, res, next) {
req.con = con
next()
})
app.use("/", require("./routes/routes"));
// Handling errors
//* Handling not mapped routes
app.use((req, res, next) => {
const error = new Error("Not found");
error.status = 404;
next(error);
});
//* Handling thrown or server errors
app.use((error, req, res, next) => {
res.status(error.status || 500);
res.json({
error: {
message: error.message,
},
});
});
app.listen(port, () => {
console.log(`App running on port ${port}.`)
})
And this is my router file
const express = require("express")
const router = express.Router()
const userController = require("../../controllers/usersController.js")
router.get("/", userController.getUsers)
router.get("/:id", userController.getUserById)
router.post("/create", userController.create)
router.put("/:id", userController.edit)
router.delete("/:id", userController.delete)
module.exports = router
when i go to postman and try any of these request this is what i get
{
"error": {
"message": "Not found"
}
}
Please if anyone has any idea why it's not working do share with me

I'm using node.js and I keep getting an error message: Error: connect ETIMEOUT ,

I'm using Node.js to make a networking app equipped with a database and I keep getting an error message:
Error: connect ETIMEOUT,
app.js
const express = require('express')
const mysql = require('mysql')
const dotenv = require('dotenv')
const path = require('path')
const cookieParser = require('cookie-parser')
const app = express()
dotenv.config({path:'./.env'})
app.set('view engine', 'hbs')
const publicDirectory = path.join(__dirname, './public')
app.use(express.static(publicDirectory))
app.use(express.urlencoded({extended: false}))
app.use(express.json())
app.use(cookieParser())
const db = mysql.createConnection({
host: process.env.DATABASE_HOST,
user: process.env.DATABASE_USER,
database: process.env.DATABASE,
password: process.env.DATABASE_PASSWORD
})
db.connect( (error) => {
if(error){
console.log(error)
}else{
console.log('DB Connected!')
}
})
app.use('/', require ('./routes/pages'))
app.use('/auth', require ('./routes/auth'))
app.listen(5000, () => {
console.log('Your Connected To Port 5000')
})
I store most of my important info in a .env file for security purposes
.env
DATABASE = bullshit
DATABASE_USER = username
DATABASE_HOST = 192.168.1.3
DATABASE_PASSWORD = password
JWT_SECRET = mysupersecretpassword
JWT_EXPIRES_IN = 90d
JWT_COOKIE_EXPIRES = 90
auth.js
const express = require('express')
const authController = require('../controllers/auth')
const router = express.Router()
router.post('/register', authController.register)
router.post('/login', authController.login)
module.exports = router
pages.js
const express = require('express')
const router = express.Router()
router.get('/', (req,res) => {
res.render('index')
})
router.get('/register', (req,res) => {
res.render('register')
})
router.get('/login', (req,res) => {
res.render('login')
})
router.get('/profile', (req,res) => {
res.render('profile')
})
module.exports = router
someone told me to change the host to my ip address and so I did. But when I did that's when I got the ETIMEOUT error message. PLEASE HELP

Resources