How to render pages in nodejs with Router - node.js

how I can render my "firstsolution.ejs" page?
I have "server.js", "routes" folder which contain "firstsolution.ejs" and "views" folder which contain "solutions" folder and solutions folder contain "solution1.ejs"
enter image description here
server.js code is:
const fisrtsolution = require("./routes/firstsolution");
firstsolution.ejs code is:
const express = require("express")
const router = express.Router();
router.get("/", function(req, res) {
res.render("./solutions/solution1");
});
module.exports = router;
but when I try to enter "http://localhost:3000/firstsolution" I see "Cannot GET /firstsolution"

You forgot to include the route in the app :
const express = require("express");
const bodyParser = require("body-parser");
const mongoose = require("mongoose");
require('dotenv/config');
const app = express();
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(express.static("public"));
app.set("view engine", "ejs"); // IMPORT ROUTES
const firstsolution = require("./routes/firstsolution");
app.use('/firstsolution', firstsolution); // <--------- here
mongoose.connect( process.env.DB_CONNECTION,{ useUnifiedTopology: true,useNewUrlParser: true }, () => console.log("connected to DB") );
const port = 3000;
app.listen(port, () => console.log(server ${port}))

Try this, I hope my code will help you.
server.js code is:
app.use(require('./routes/firstsolution'));
firstsolution.ejs code is:
const express = require("express")
const router = express.Router();
router.get("/", function(req, res) {
res.render("solutions/solution1");
});
module.exports = router;

Related

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;

app.use() requires a middleware function error

In a nodejs project I'm getting this error : 'app.use() requires a middleware function error at the line 7 of this file :
const Router = require('./route');
const express = require('express');
const app = express();
const port = 3001;
app.use(express.json());
app.use(Router);
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`);
});
and I really don't get why I'm getting this error.
here are the routes files
const ProduitRouter = require('./produit');
const router = require("express").Router();
router.use("/produit", ProduitRouter);
module.exports = router;
const ProduitControleur = require("../controleur/produitDB");
const Router = require("express-promise-router");
const router = new Router;
//const router = require("express").Router();
router.get('/:id', ProduitControleur.getProduit);
router.post('/', ProduitControleur.postProduit);
router.patch('/', ProduitControleur.updateProduit);
router.delete('/', ProduitControleur.deleteProduit);
module.exports = router;
Try this.
In app.js
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const cors = require('cors');
const http = require('http');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.use(cors());
require('./routes')(app); // path of file in which all your routes are defined.
module.exports = app;
in router file where all routes are define.
const express = require('express');
const router = express.Router();
const controller = require('path of controller');
router.post('/upload/file', verifyToken, controller .functionName);
module.exports = router;
As I can see, there is no imports for Router file

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

Dynamic BaseUrl in ExpressJs

I'm trying to set the base URL for an Express app on startup.
I can hardcode the base URL and it works just fine:
app.use("/mybaseurl", routes);
However, if I try to use a variable instead which I can export on startup, it fails:
const baseUrl = "/mybaseurl";
app.use(baseUrl, routes);
The above doesn't work.
What am I missing?
test this code, work for me: http://localhost:3000/test
app.js:
const express = require('express');
const userRouter = require('./user');
const app = express();
app.use(express.json());
const baseUrl = '/test';
app.use(baseUrl, userRouter);
app.listen(3000, ()=> {
console.log('Server is up on port ', 3000)
});
user.js:
const express = require('express');
const router = new express.Router();
router.get('/', async (req, res) => {
res.status(200).send('hello');
});
module.exports = router;

NODE Cannot GET routes function

I have created a folder testint
My testint/app.js having following code
const express = require('express'); const path = require('path');
const bodyParser = require('body-parser'); const cors = require('cors');
const passport = require('passport'); const mongoose = require('mongoose');
const app = express(); const port = 7000; app.use(cors());
app.use(bodyParser.json());
app.use('/users', users); //Not working
app.get('/',(req,res) => {
res.send("Invalid Endpoint");
});
app.listen(port, () =>{
console.log('Server started on port '+ port);
});
testint/routes/users.js contains :
const express = require('express'); const router = express.Router();
res.send('Authenticate');
router.get('/register',(req, res, next) => {
res.send('REGISTER');
});
module.exports = router;
If I run http://localhost:7000/users/register
Am getting :
Cannot GET /users/register
I dint know where am wrong and am new to node any help will be appreciated.
I got solution. I didn't include
const users = require('./routes/users');
in app.js
and res.send('Authenticate'); in users.js is not required for instance.

Resources