Multiple Routes in node express backend - node.js

I am new in node js and want to build an application in which they are multiple APIs and all are settled in routes folder but here is the problem when I tried to call the API in index.js(main file) its only take one route either userAPI or cleanerAPI.
As both APIs have different URL.
var mongoose = require ('mongoose');
var express = require('express');
const bodyParser = require('body-parser');
var app = express();
const routerUser= require('./routes/userAPI')
mongoose.connect('mongodb://localhost:27017/Covid');
app.use(bodyParser.json());
app.use('/',router);
app.listen(4000,function(){
console.log("Server Running on 4000")
});

you can try this one also.
Main file(index.js or server.js)
const appRoutes = require('./Routes')
appRoutes(app)
Routes(index.js)
module.exports = app => {
app.use("/user", require('./users'));
app.use("/cleaner", require('./cleaner')); };
Routes(users.js)
const express = require('express');
const router = express.Router();
router.route('/list')
.post(function(req,res){......});
module.exports = router;

Related

Why my incoming request not hitting my node.js(express ) server?

I have a node.js(express) app in which i have defined all my routes, controllers and all that.
customer.route.js
const express = require('express');
const Controller = require('../controllers/customer.controller');
const { customerValidationRules, validate } = require('../middlewares/request- validator.middleware');
const router = express.Router();
router.route('/create').post(customerValidationRules, validate, Controller.create);
module.exports = router;
my index.js file inside routes folder
const express = require('express');
const cors = require('cors');
const responseUtil = require('../helpers/response.helper');
const customerR = require('../routes/customer.route');
const router = express.Router();
router.use(cors());
router.use('/customers', customerR);
/** Returned when requested api url not found **/
router.use((req, res) => responseUtil.sendNotFound(res));
module.exports = router;
And my app.js(root file)
const routes = require('./routes');
const app = express();
app.use('/api/v1', routes);
Now when i am hitting my api via postman with this api url
http://localhost:3003/api/v1/customers/create
So it keeps going and none of my logs priting on the console it means that request is not coming to my server now. Can any one let me know what'st he issue in it.
Because routes in Express router are not chained.
If you have
app.use('/customers',customerRouter)
Then you have to in your customerRouter define the whole route:
router.post('/customers/create', yourPostStuff)

Node declaring express many files difference?

my English not very well but
My question is:
in this file
index.js
const express = require('express');
const app = express();
app.use(require('./routes/index.js'));
app.listen(3000);
routes/index
const express = require('express');
const app = express();
app.get(....
module.exports = app;
because I have to declare app again, is it necessary to create or instantiate express multiple times in multiple files?
what is the difference between app = express() in index.js and app = express() in routes/index.js
thanks
I am assuming that you are trying to implement routing in your Node.js application. If I am right then correct code of
routes/index.js
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', ...
module.exports = router;
As you can see in above code that you don’t need to reinitialize the app again into the index.js. Instead you have to initialize the 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

App.route is not a function when accessing it in a controller function for express routing

I am trying to create a simple API using NodeJS.
I plan to separate the main api.js, route-definitions.js, route-logic.js in their own separate folders for them to be more structured and organized.
However, when I call app.route() in my route-definitions.js, it fails at compilation and saying that app.route is not a function.
server.js
var express = require('express')
var api = require("./api/api.js");
app = express();
port = process.env.PORT || 3000;
app.use('/', api);
app.listen(port);
api.js
var express = require('express');
var router = express.Router();
router.use('/read', require('./routes/route-definitions'));
module.exports = router;
route-definitions.js
'use strict';
module.exports = function(app) {
var operations = require('../controllers/route-logic.js')
//Route to check if a file with the same file name already exists
app.route('/getItems')
.post(operations.getItems);
}
When I try to run the API locally, and call /read/getItems, I get the error:
TypeError: app.route is not a function
What am I missing? I'm fairly new to Node and Express, but I know I'm not passing the app instance correctly or it is not set globally.
You can solve it by creating a child router in route-definitions.js
var router = require('express').Router();
var operations = require('../controllers/route-logic.js');
router.post('/getItems', operations.getItems);
module.exports = router;
In api.js you need to pass the router to the function you are exporting in route-definitions.js
var express = require('express');
var router = express.Router();
router.use('/read', require('./routes/route-definitions')(router));
module.exports = router;
You've used app in the route-definitions.js but looks like you forgot to pass it to that module.
Please have a look at below code:
var express = require('express');
var router = express.Router();
var app = express();
router.use('/read', require('./routes/route-definitions')(app));
module.exports = router;

Getting "Cannot GET/" from API test in Node.JS

I am new to Node.JS I am trying to compile a node with express API but without success, Tried to debug the App just stops in the first module import, I create similar app from tutorial ran well but not saving input data, code bellow:
URL: localhost:3000/api/v1/students
Server.js
// Dependences
var bodyParser = require("body-parser");
var express = require("express");
var mongoose = require("mongoose");
var app = express();
//connect to database
mongoose.connect("mongodb://localhost/rest_test");
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
app.get("/api/v1",require("./routes/api"));
app.listen(3000,
function(req,resp)
{
console.log("is Working bitch!");
});
./routes/api.js
var express = require("express");
var router = express.Router();
var Students = require("../models/Students");
Students.methods(["get","post","put","delete"]);
Students.register(router, "/Students");
module.exports = router;
./models/Students.js
var restful = require("node-restful");
var mongoose= restful.mongoose;
var StudentSchema = new mongoose.Schema(
{
name : String,
course : String
});
module.exports = restful.model("Students",StudentSchema);
Solved,
Instead of get must be use:
app.use("/api/v1",require("./routes/api"));

Resources