getting Can't find / on this server while deploying my app on localhost - api

when I tried to connect my application with API I'm getting error in my localhost saying
"status": "fail",
"message": "Can't find / on this server",
"error": { statusCode: 404, status: "fail", isOperational: true },
"stack": "Error: Can't find / on this server\n at C:\\Users/*/*app.js:66",
here is my app.js
const express = require("express");
const morgan = require("morgan");
const rateLimit = require("express-rate-limit");
const helmet = require("helmet");
const mongoSanitize = require("express-mongo-sanitize");
const xss = require("xss-clean");
const hpp = require('hpp');
const AppError = require("./API/Utils/appError");
const globalErrorHsndler = require("./API/controllers/errorController");
const usersRouter = require("./API/routes/usersRoute");
const app = express();
app.use(express.json({ limit: "10kb" }));
// DATA SANITIZATION against NoSQL query injection
app.use(mongoSanitize());
// DATA SANITIZATION against site script XSS
app.use(xss());
// PREVENT PARAMETER POPULATION
app.use(
hpp({
whitelist: [
"duration",
"difficulty",
"price",
"maxGroupSize",
"ratingsAverage",
"ratingsQuantity",
],
})
);
// SECURE HEADER HTTP
app.use(helmet());
//RATE LIMIT
const apiLimiter = rateLimit({
windowMs: 60 * 60 * 1000, // 15 minutes
max: 100, // limit each IP to 100 requests per windowMs
message: "Too many requests, please try again later"
});
// apply to specific routes
app.use("/api", apiLimiter);
app.use(morgan("dev"));
//CUSTOM MIDDLE WARE
app.use((req, res, next) => {
console.log("Hey i am from middleware function 👋");
next();
});
app.use((req, res, next) => {
req.requestTime = new Date().toISOString();
next();
});
app.use("/api/v1/users", usersRouter);
//ERROR SECTION
app.all("*", (req, res, next) => {
console.log(`Received request for url: ${req.originalUrl}`);
const error = new AppError(`Can't find ${req.originalUrl} on this server`, 404);
console.log(`Data inside next AppError: ${error}`);
next(error);
});
//GLOBAL ERROR HANDLEING
app.use(globalErrorHsndler);
module.exports = app;
here is my userRouter.js
const express = require("express");
const userControllers = require("./../controllers/userControllers");
const authController = require("./../controllers/authController");
const router = express.Router();
router.post("/signup", authController.signup);
router.post("/login", authController.login);
router.post("/forgotPassword", authController.forgotPassword);
router.patch("/resetPassword/:token", authController.resetPassword);
router.patch("/updateMyPassword", authController.protect, authController.updatePassword);
router.patch("/updateMe", authController.protect, userControllers.updateMe);
router.delete("/deleteMe", authController.protect, userControllers.deleteMe);
//ROUTERS USERS
router
.route("/")
.get(userControllers.getAllUsers)
.post(userControllers.createUser);
router
.route("/:id")
.get(userControllers.getSingleUser)
.patch(userControllers.updateUser)
.delete(userControllers.deleteUser);
module.exports = router;
and here is server.js
const dotenv = require("dotenv");
const mongoose = require("mongoose");
const app = require("./app");
const next = require("next");
const port = process.env.PORT || 3000;
const dev = process.env.NODE_ENV !== "production";
const server = next({ dev });
const handle = server.getRequestHandler();
process.on("uncaughtException", err=>{
console.log("uncaughtException Shutting down Application");
console.log(err.name, err.message);
process.exit(1);
});
dotenv.config({ path: "./config.env" });
const DB = process.env.DATABASE.replace(
"<PASSWORD>",
process.env.DATABASE_PASSWORD
);
mongoose
.connect(DB, {
useCreateIndex: true,
useFindAndModify: false,
useNewUrlParser: true,
})
.then((con) => {
console.log("DB Connection Successfully");
})
server.prepare().then(() => {
app.get("*", (req, res) => {
return handle(req, res);
});
app.listen(port, () => {
console.log(`App running on port ${port}....`);
});
});
process.on("unhandledRejection", (err) => {
console.log("unhandledRejection Shutting down Application");
console.log(err.name, err.message);
server.close(() => {
process.exit(1);
});
});
I need to ask from experts as I'm new to this

Related

cookie-session, socket.io fails to store socket.id in sessions

server.js
const express = require("express");
const cookieSession = require("cookie-session");
const socketIo = require("socket.io");
const app = express();
app.use(
cookieSession({
name: "session",
keys: ["key1", "key2"],
})
);
app.use((req, res, next) => {
console.log(req.session);
next();
});
app.get("/", (req, res) => {
res.sendFile("./index.html", { root: __dirname });
});
app.get("/about", (req, res) => {
const connectionId = req.session.connectionId;
res.send(`About. connectionId: ${connectionId}`);
});
const server = app.listen(1234);
const io = socketIo(server);
io.on("connection", (socket) => {
const connectionId = Math.random().toString(36).substring(2);
socket.request.session.connectionId = connectionId;
// socket.request.session.save();
});
My problem is that when I call the connect event on the client, but on the server socket.request.session returns undefined so I can't set a unique value in the cookie-session. What is it connected with?

Express. Failed to load resource: the server responded with a status of 404

I am trying to make a post request using router.post and I keep getting " the server responded with a status of 404.
I have a routes folder with the file usersRoute.js :
const express = require("express");
const router = express.Router();
const User = require("../models/userModel");
router.post("/login", async(req, res) => {
const { username, password } = req.body;
try {
const user = await User.findOne({ username, password });
if (user) {
res.send(user);
} else {
return res.status(400).json(error);
}
} catch (error) {
return res.status(400).json(error);
}
});
router.post("/register", async (req, res) => {
try {
const newuser = new User(req.body);
await newuser.save();
res.send("User registered successfully");
} catch (error) {
return res.status(400).json(error);
}
});
module.exports = router;
I'm also using this method to make a get request to another endpoint in a carsRoute.js file which looks like this (the get request works) :
const express = require("express");
const router = express.Router();
const Car = require("../models/carModel");
router.get("/getallcars", async(req,res) => {
try {
const cars = await Car.find()
res.send(cars)
} catch (error) {
return res.status(400).json(error);
}
})
module.exports = router;
Finally, I export them into server.js which looks like this :
const express = require('express');
const app = express();
const port = process.env.port || 5000;
const dbConnect = require('./db');
app.use(express.json())
app.use('/api/cars/' , require('./routes/carsRoute'))
app.use('/api/users/', require('./routes/usersRoute'))
app.get('/', (req,res) => res.send('Hello World') )
app.listen(port, () => console.log(`Node Js Server Started on port ${port}`))
I do not think i missed any "/" or have any additional ones.

Run socket.io from an express route

I have researched on this but nothing seems to satisfy my need. I have an express route connected to a mongodb. Below is part of the code.
const express = require('express');
const socketIo = require("socket.io");
const dbconnect = require("./models");
const handle = require("./handlers");
const routes = require("./routes");
const app = express();
app.use('/messages', routes.messages);
const PORT = 3000;
const server = app.listen(3000, function() {
console.log(`Listening on 3000`);
dbconnect().then(() => {
console.log("MongoDb connected");
});
});
const io = socketIo(server);
io.on('connection', function(client) {
console.log('Connected...');
});
My route looks like this:
const router = require('express').Router();
const handle = require('../handlers/messages');
router.post('/unread_messages', handle.unread_messages);
module.exports = router;
My handler looks like this:
const db = require("../models");
exports.unread_messages = async (req, res, next) => {
try {
const unreadmessages = await db.messages.countDocuments({ $and: [{receiver: req.body.receiver},
{ messageread: false }]});
return res.json({ unreadmessages });
} catch (err) {
return next({ status: 400, message: `Cannot get unread messages ${err}` });
}
};
I would like to add socket to the "/unread_messages" route so that I get an update of the count of unread messages in realtime. How do I do that?

timeout async callback testing with sinon jest supertest to simulate error 500 on express api

I am testing an api with all http 500 errors.
Here I try to use sinon.stub to test on a failing server and get a 500 error, but I get a timeOut async callback, or if I use my app a successfull 200 response statusCode as if sinon.stub has no effect. I must miss something and I am stucked...
would you see a horrifying error below ?
thanks for your precious help
process.env.NODE_ENV = "test";
const app = require("../../app");
const request = require("supertest");
const sinon = require("sinon");
// /************************** */
const usersRoute = require("../../routes/Users");
const express = require("express");
const initUsers = () => {
const app = express();
app.use(usersRoute);
return app;
};
describe("all 5xx errors tested with stub", function () {
it("should return a 500 when an error is encountered", async (done) => {
let secondApp;
sinon.stub(usersRoute, "post").throws(
new Error({
response: { status: 500, data: { message: "failed" } },
})
);
secondApp = initUsers(); //==========> Timeout Async Callback
//secondApp = require("../../app"); //==============> gives a 200 instead of 500
const fiveHundredError = await request(secondApp)
.post("/users/oauth?grant_type=client_credentials")
.send({
username: "digitalAccount",
password: "clientSecret",
});
expect(fiveHundredError.statusCode).toBe(500);
//sinon.restore();
done();
});
});
app is using express.Router to get users route :
const express = require("express");
const router = express.Router();
const axios = require("axios");
router.post("/users/oauth", async (req, res) => {
//if (all missing parts)
//else {
try {
if (req.fields) {
const response = await axios.post(
`${base_url}oauth/token?grant_type=${req.query.grant_type}`,
{},
{
auth: {
username: req.fields.username,
password: req.fields.password,
},
}
);
res.json(response.data);
}
} catch (error) {
return res.status(error.response.status).json(error.response.data);
}
}
});
module.exports = router;
See server.js :
const app = require("./app");
const port = process.env.PORT || 5000;
app.listen(port, () => console.log(`server starting on port ${port}!`));
and app.js :
// private environment:
require("dotenv").config();
const express = require("express");
const formidableMiddleware = require("express-formidable");
const cors = require("cors");
const app = express();
app.use(formidableMiddleware());
app.use(cors());
const usersRoute = require("./routes/Users");
app.use(usersRoute);
app.get("/", (req, res) => {
res.status(200).send("Welcome to Spark Admin back end!");
});
app.all("*", (req, res) => {
return res.status(404).json({ error: "Web url not found" });
});
module.exports = app;
I finally opted for 'nock' and deleted 'sinon'
const nock = require("nock");
const axios = require("axios");
describe("POST login: all 5xx errors tested with nock", function () {
it("should return a 500 when an error is encountered", async (done) => {
const scope = nock("http://localhost:5000")
.post(
"/users/oauth",
{},
{
username: "blibli",
password: "blabla",
}
)
.reply(500, {
response: {
statusCode: 500,
body: { error: "AN ERROR OCCURED" },
},
});
try {
await axios.post(
"http://localhost:5000/users/oauth",
{},
{
username: "blibli",
password: "blabla",
}
);
} catch (e) {
expect(e.response.status).toBe(500);
}
done();
});
});

Using Express Router with Next.js

I'm trying to use the Express Router with Next.js using their custom-express-server example as my boilerplate. The only difference is that I'm trying to define the routes externally on routes/router.js as follows:
Code in server.js:
const express = require('express')
const next = require('next')
const port = parseInt(process.env.PORT, 10) || 3000
const dev = process.env.NODE_ENV !== 'production'
const app = next({ dev })
const handle = app.getRequestHandler()
const routes = require('./routes/router')
app.prepare()
.then(() => {
const server = express()
server.use('/', routes)
server.get('*', (req, res) => {
return handle(req, res)
})
server.listen(port, (err) => {
if (err) throw err
console.log(`> Ready on http://localhost:${port}`)
})
})
module.exports = app;
Code in routes/router.js:
const express = require('express'),
app = require('../server.js'),
router = express.Router();
router.get('/a', (req, res) => {
return app.render(req, res, '/b', req.query)
})
router.get('/b', (req, res) => {
return app.render(req, res, '/a', req.query)
})
router.get('/posts/:id', (req, res) => {
return app.render(req, res, '/posts', { id: req.params.id })
})
module.exports = router;
At this point, even when I'm importing "app" from server.js, app is not available within router.js.
Is my logic incorrect?
If it's not, then why is app not available within router.js?
Just solved it. This issue is known as a circular dependency, and it should be avoided at all costs... unless the pattern you're using (like the boilerplate I used, I guess...) requires it.
To solve it, just export from file "A" the dependency that file "B" uses before you require file "B" on file "A".
...And that's it pretty much.
You might also try using next-routes, which I use on all of my Next project:
// server.js
const { createServer } = require('http');
const next = require('next');
const routes = require('./routes');
const port = parseInt(process.env.PORT, 10) || 3000;
const dev = process.env.NODE_ENV !== 'production';
const app = next({ dev });
const handler = routes.getRequestHandler(app);
app.prepare().then(() => {
createServer(handler).listen(port, err => {
if (err) {
throw err;
}
console.log(`> Ready on http://localhost:${port}`);
});
});
Then you can configure your routes in the routes.js file without accessing the app:
// routes.js
const nextRoutes = require('next-routes');
const routes = (module.exports = nextRoutes());
routes
.add('landing', '/')
.add('blog', '/blog', 'blog')
.add('blog-post', '/blog/:postId', 'blog')