Express Router unable to route to another folder - node.js

I am trying to create a Node JS app with mongoDB. from main app.js I am trying to redirect to another folder named "services". Here is my folder structure -
Here is my app.js -
const express = require('express')
const mongoose = require('mongoose')
const dotenv = require('dotenv')
const cors = require('cors')
const bodyParser = require('body-parser')
const app = express()
const users = require('./userSchema')
const services = require('./services/index')
app.use('/services', express.static('/services'))
app.use(express.static('/'));
app.use(cors())
dotenv.config()
const port = 3000
mongoose.connect(process.env.DB_CONNECT,
{
useUnifiedTopology: true,
useNewUrlParser: true,
useFindAndModify: false
})
.then(() => console.log('Connected to mongoDB'))
.catch(err => console.error('Could not connect to MongoDB..', err))
const jsonParser = bodyParser.json()
app.get('/allName', async (req, res) => {
let data = await users.find()
res.status(200).send(data)
})
app.listen(port, () => console.log(`Demo app listening on port ${port}!`))
Here is my index.js file inside services folder -
var express = require('express')
var router = express.Router()
router.get('/', function (req, res) {
res.send('Birds home page')
})
router.get('/about', function (req, res) {
res.send('About birds')
})
module.exports = router
While running http://localhost:3000/allName , it is working fine. But if i try to run http://localhost:3000/services, it is throwing Cannot GET /services. I am not able to fix this.
How to redirect to index.js from app.js when users trigger http://localhost:3000/services?

change
app.use('/services', express.static('/services'))
into
app.use('/services', services);
express.static is used to serve static files, looks like you wish to use a router and not return static files. This is why the server does not respond as you like

Yes, because you haven't properly added the reference of the service routes.
Remove express.static from the reference because you already have imported the service routes in a variable then just use it and it will work as expected.
Just a note. Express.static is used to load/use the static files like css or images or something like that.
Check the code below.
const express = require('express')
const mongoose = require('mongoose')
const dotenv = require('dotenv')
const cors = require('cors')
const bodyParser = require('body-parser')
const app = express()
const users = require('./userSchema')
const services = require('./services/index')
**app.use('/services', services)** // change this into your code.
app.use(express.static('/'));
app.use(cors())
dotenv.config()
const port = 3000
mongoose.connect(process.env.DB_CONNECT,
{
useUnifiedTopology: true,
useNewUrlParser: true,
useFindAndModify: false
})
.then(() => console.log('Connected to mongoDB'))
.catch(err => console.error('Could not connect to MongoDB..', err))
const jsonParser = bodyParser.json()
app.get('/allName', async (req, res) => {
let data = await users.find()
res.status(200).send(data)
})
app.listen(port, () => console.log(`Demo app listening on port ${port}!`))

Related

Node.js Cannot find get route

const express = require("express");
const app = express();
const mongoose = require("mongoose");
const Observation = require("./schema/dreamWorld");
const bodyParser = require("body-parser");
const cors = require("cors");
app.get("/", (req, res) => res.send("Hello World"));
app.listen(3000, () => console.log("Server started on port 3000"));
app.use(cors, bodyParser.json());
app.get("/world", (req, res) => {
return res.status(200).json({ message: "HAppy?" });
});
const mongoDB = "mongodb://127.0.0.1/test";
mongoose.connect(mongoDB, { useNewUrlParser: true, useUnifiedTopology: true });
in the above coding that I am testing in Postman! I can connect to "/" route and postman displays hello world! but when I search "/world" get route in postman it keeps on loading forever and does not fetch anything.
I have made sure server is running with correct Port number. what am I doing wrong here?
The body-parser no more necessary if use express V4.16 or later.
It is included into express.js.
More detail is explained in here.
This code will be works.
const express = require("express");
const mongoose = require("mongoose");
const Observation = require("./schema/dreamWorld");
const cors = require("cors");
const app = express();
app.use(cors())
app.get("/", (req, res) => res.send("Hello World"));
app.get("/world", (req, res) => {
return res.status(200).json({ message: "Happy?" });
});
const mongoDB = "mongodb://127.0.0.1/test";
mongoose.connect(mongoDB, { useNewUrlParser: true, useUnifiedTopology: true });
app.listen(3000, () => console.log("Server started on port 3000"));

Mongo DB not connecting to NodeJS after Heroku deployment

I've a MERN app (Mongo Express React Node) that works locally, and connects to my MongoDB database, getting data.
The React front-end works after I deploy it to Heroku, but Nodejs won't connect to MongoDB on Heroku.
The environment variables like MONGO_URI stored as Heroku config variables, works perfectly fine, yet it just won't connect to my MongoDB.
The Heroku logs shows the error message: DISCONNECTED FROM MONGO DB from my server.js file.
How can I solve this?
server.js file
const express = require("express");
const dotenv = require("dotenv");
const cookieParser = require("cookie-parser");
const mongoose = require("mongoose");
const cors = require("cors");
const path = require("path");
dotenv.config();
const authRouter = require("./routes/auth");
const blogRouter = require("./routes/blog");
const userRouter = require("./routes/user");
const app = express();
app.use(express.json());
app.use(cookieParser());
app.use(cors());
app.use("/api/auth", authRouter);
app.use("/api/user", userRouter);
app.use("/api/blog", blogRouter);
if(process.env.NODE_ENV === "production"){
app.use(express.static("client/build"));
app.get("*", (req, res) => {
res.sendFile(path.resolve(__dirname, "client", "build", "index.html"));
});
}
const connect = () => {
mongoose
.connect(process.env.MONGO_URL,
{useNewUrlParser: true,
useUnifiedTopology: true,
useNewUrlParser: true})
.then(() => {
console.log("CONNECTED TO THE MONGO DB");
})
.catch((err) => {
console.log(err);
mongoose.disconnect(() => {
console.log("DISCONNECTED FROM MONGO DB");
});
})
};
app.listen(process.env.PORT || 8000, () => {
connect();
console.log("MONGO_URL", process.env.MONGO_URL);
console.log("PASSCODE", process.env.PASSCODE);
console.log(`LISTENING ON PORT ${process.env.PORT}`);
})
Your environment variable to connect to MongoDB database has to be MONGO_URI, not MONGO_URL.
Otherwise it won't work.

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

Express 4.17 req.body is empty

I'm hoping you can help me out here because after trying over a dozen s/o solutions and reading the express docs several times, I'm stumped. I'm building a Node app that will (in the end) accept a POST from the front end app, persist it to Mongo then allow back end users to manipulate the data. I am just getting going, trying to get the POST route working and have this so far:
app.js:
const express = require("express");
const cors = require("cors");
const mongoose = require('mongoose');
const AppData = require("./model/AppData");
const uri = "mongodb://localhost:27017/lunch"
mongoose.connect(uri, { useNewUrlParser: true, useCreateIndex: true, useUnifiedTopology: true });
const connection = mongoose.connection;
const router = require("./routes/index");
const PORT = 3005;
const app = express();
app.use(cors());
app.use("/", router);
app.use(express.raw({type: "application/json"}));
app.use(express.json({strict: false}));
connection.once('open', () => {
console.log('👍Successfully connected to MongoDB👍');
});
app.listen(PORT, function () {
console.log(`🚀The Backend Server is up and running on port ${PORT}🚀`);
});
index.js (routes...plan on changing the name)
const express = require('express');
const router = express.Router();
const appDataController = require('../controllers/appDataController');
router.post('/submit', appDataController.createAppData);
module.exports = router;
and appDataController.js:
const mongoose = require('mongoose');
const AppData = mongoose.model('AppData');
exports.createAppData = (req, res) => {
let reqData = req.body;
console.log(reqData);
res.send(reqData);
}
Simple enough, really, but when I grab Postman and set up a request using body/raw/json and send
{
"name": "John",
"age": "21"
}
I always see that body is undefined. From everything I've seen, I'm not doing anything wrong, but the result clearly indicates otherwise...What is it that I've missed?
Its because your using your express.json middleware after the routes, change this:
const express = require("express");
const cors = require("cors");
const mongoose = require('mongoose');
const AppData = require("./model/AppData");
const uri = "mongodb://localhost:27017/lunch"
mongoose.connect(uri, { useNewUrlParser: true, useCreateIndex: true, useUnifiedTopology: true });
const connection = mongoose.connection;
const router = require("./routes/index");
const PORT = 3005;
const app = express();
app.use(cors());
app.use(express.raw({type: "application/json"}));
app.use(express.json({strict: false}));
app.use("/", router); // this need to be here
connection.once('open', () => {
console.log('👍Successfully connected to MongoDB👍');
});
app.listen(PORT, function () {
console.log(`🚀The Backend Server is up and running on port ${PORT}🚀`);
});
first comes the middlewares and then the routes(depends on the middleware your using ofcurse).
You should also include urlencoded option to get the body on x-www-form-urlencoded body for POST requests.
const app = express();
app.use(cors());
app.use(express.raw({type: "application/json"}));
app.use(express.json({strict: false}));
app.use(express.urlencoded({extended: false})); // include this line
app.use("/", router);

nodejs connection fail to database

i'm trying to build a simple rest api based on node.js + mongodb
i'm using https://cloud.mongodb.com/ and my connection string is 1000% correct
i keep having this problem sometimes it work for me all the day no issue
and sometimes it doesn't wanna connect and i changed nothing in the code
anyone is having similar issues?
const mongoose = require('mongoose');
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
require('dotenv/config');
app.use(bodyParser.json());
// Import routes
const postsRoute = require('./routes/posts');
app.use('/posts', postsRoute);
//mongodb connect
mongoose.connect(process.env.db_access, { useNewUrlParser: true, useUnifiedTopology: true },
() => {
console.log('connected');
}
);
//ROUTES
app.get('/', (req,res) => {
res.send('home boi');
});
//listening port
app.listen(3000);

Resources