app.use() requires a middleware function error - node.js

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

Related

Browser showing "Cannot GET /api/posts/ " instead of "hello" from res.send('hello')

My index.js file:
//Dependencies
const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');
const posts = require('./routes/api/posts.js');
//Configuration
const port = process.env.PORT || 5000;
//App object
const app = express();
//Middleware
app.use(bodyParser.json());
app.use(cors());
//Main app
app.use('api/posts',posts);
//Starting server
app.listen(port,()=>{
console.log(`server running at ${port}`);
});
My Api file:
//Dependencies
const express = require('express');
const mongodb = require('mongodb');
//Mini app
const router = express.Router();
//Get post
router.get('/',(req,res)=>{
res.send('hello');
});
//Add post
//Delete post
module.exports = router;
I'm expecting to get "hello" in my browser but constantly getting "Cannot GET /api/posts/" in firefox and postman. What should I do now?
Correction :-
//Main app
app.use('/api/posts',posts);

Cannot GET /api

I have a problem with my post data to the server. Not sure why i get an error for get when i changed my rout to post.
routes/feedback.js
const express = require("express");
const router = express.Router();
const { emailFeedback } = require("../controllers/feedback");
router.post("/feedback", emailFeedback);
module.exports = router;
server.js
const express = require("express");
const morgan = require("morgan");
const bodyParser = require("body-parser");
const cors = require("cors");
require("dotenv").config();
// import routes
const feedbackRoutes = require("./routes/feedback");
// app
const app = express();
// middlewares
app.use(morgan("dev"));
app.use(bodyParser.json());
app.use(cors());
// routes
app.use("/api", feedbackRoutes);
// port
const port = process.env.PORT || 8000;
app.listen(port, () => console.log(`Server is running on port ${port}`));
I believe the usual syntax for an express post route is as follows:
router.post("/feedback", function(req, res){
//grabbing the request body
console.log(req.body);
console.log(req.bodt);
//posting the request
res.json(req.body);
});
A callback function needs to be passed in and receive those request and response parameters (req, res).

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;

How to render pages in nodejs with Router

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;

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