Parameter express can't be passed with require - javascript

app.js
const express = require("express");
const app = express();
app.use("/", require("./routers.js")(app));
app.listen(3000);
router.js
module.exports = function (app) {
console.log(app);
app.get("/", (req, res) => {
res.json(5);
});
};
The error given by the Console is: " TypeError: Router.use() requires a middleware function but got an undefined "
I don't understand why I can't pass the express app(app.js) through routers( in this way I don't redeclare the express and app variable in router.js ).

Don't pass app to routes better to create a new router and pass to the app.
router.js
const express = require("express");
const router = express.Router();
router.get("/", (req, res) => {
res.json(5);
});
module.exports = router;
app.js
app.use("/", require("./routers.js"));
As you mention in the comment, you don't have to add an inside app.use
module.exports = function (app) {
app.get("/", (req, res) => {
res.json(5);
});
};
// app.js
require("./routers.js")(app);

The use method of Express needs a callback of three parameters, not the app itself, so you need something like this:
In routes.js
exports.doSomeThing = function(req, res, next){
console.log("Called endpoint");
res.send("Called endpoint");
}
In your index.js
const Express = require("express");
const app = Express();
const routes = require("./routes");
app.use("/", routes.doSomeThing);
app.listen(3030, () => {
console.log("Listening on port 3030");
});
This approach doesn't need to include the express router but this may not be adecuate for big scale projects I recommend you to read express router documentation:
https://expressjs.com/es/guide/routing.html#express-router

Related

external routing is not working in express js

here is my main.js file
import express from 'express';
// route file are import here
import router from "./user-route/admin-route.js";
// **************** global variable are define here
const app = express();
const port = 5000;
app.use(express.json());
app.use(("./user-route/admin-route.js"));
/// ***************** routing are created are here
app.get("/", (req, res) => {
res.send("Hello from the server");
});
// ****************** server is created here
app.listen(port, () => {
console.log("Server is Ready and Running on Port 5000");
});
and here is my external routing file
import express from 'express';
const router = express.Router();
const admin = (req, res, next) => {
res.send("Hlo from the dashboard");
}
/// admin routers are defined here
router.route("/admin").get(admin);
export default router;
how I can connect the external routing with main.js file. here I am using the module method.
if i try with require method than it's work properly. i am not sure but i think problem is here
app.use(("./user-route/admin-route.js"));
Yes, this is the issue:
app.use(("./user-route/admin-route.js"));
You can't pass a filename to app.use() and expect it to work (in fact, it throws an error).
But you were close:
app.use(router);
I think what your looking for is something similar to this? What you're missing really is the app.use routing part, there are two parameters for that.
app.use('/admin', AdminRouter);
Main.js file
import express from 'express';
// route file are import here
const AdminRouter = require('./user-route/admin-route.js')
// **************** global variable are define here
const app = express();
const port = 5000;
app.use(express.json());
/// ***************** routing are created are here
app.get("/", (req, res) => {
res.send("Hello from the server");
});
app.use('/admin', AdminRouter);
// ****************** server is created here
app.listen(port, () => {
console.log("Server is Ready and Running on Port 5000");
});
external routing file
const express = require('express');
const router = express.Router();
/// admin routers are defined here
router.get('/', function(req, res, next) {
res.send('respond with a resource');
});
module.exports = router;

Express route with dynamic params not working

router.get('/:id ', (req, res) => {
res.send(req.params.id);
});
When I call this on exmaple "http://localhost/12" I will get an error called "Cannot Get /12"
Any ideas what I am missing out?
You need to register your router to main app in your index.js
In your router.js folder
const express = require('express');
const router = express.Router()
router.get('/:id ', (req, res) => {
res.send(req.params.id);
});
and in your index.js
const express = require('express');
app = express()
app.use(router)

Why I get TypeError('Router.use()

I have index.js file like this and
const express = require('express');
const app = express();
//Import Routes
const authRoute = require('./routes/auth');
//Route Middlewares
app.use('/api/user', authRoute);
app.listen(3000, () => console.log('Server Up and running'));
auth.js like this one
const router = require('express').Router();
router.post('/register', (req, res) => {
res.send('Register');
})
module.exports = router;
Why i get the TypeError('Router.use() requires a middleware function but got a ' + gettype(fn))
^
TypeError: Router.use() requires a middleware function but got a Object
at Function.use (C:\Users\xxx\Desktop\Websites\Authentication\node_modules\express\lib\router\index.js:458:13)
at Function. (C:\Users\xxx\Desktop\Websites\Authentication\node_modules\express\lib\application.js:220:21)
You may try to re-write your auth.js in the following format, I think that will solve the issue:
router.route('/register').post((req, res) => { .............

Express subrouter returns 404

I have this router (http/api/ping.js):
var express = require('express');
var router = express.Router();
router.get('/ping', function (req, res) {
res.send("You called /api/ping");
});
module.exports = router;
This router is embedded into this router (http/api/index.js):
var express = require('express');
var router = express.Router();
router.get('/', function (req, res) {
res.send('You called /api');
});
router.use('/ping', require('./ping'));
module.exports = router;
And this router is used by my Express.js app (app.js):
var http = require('http');
var express = require('express');
var bodyParser = require('body-parser');
var logger = require('./config').logger;
// Create app
var app = express();
var server = http.createServer(app)
var io = require('socket.io')(server);
// App config
app.use(bodyParser.json());
app.use('/api', require('./http/api'));
// Display requests on console
app.use(function (req, res, next) {
logger.trace(req.method, req._parsedUrl.href);
next()
});
module.exports = {
app: app,
server: server
};
When I run the app, /api returns You called /api, but /api/ping gives me a 404.
I am using Node 6.9.1 and Express ^4.14.0
I think order matters in this scenario. Try putting /ping above the / get route.
router.use('/ping', require('./ping'));
router.get('/', function (req, res) {
res.send('You called /api');
});
Also in your ping route you say the path to your route is /ping you also say it is /ping when you import it to the other router, which would make the path /api/ping/ping
change
router.get('/ping', function (req, res) {
res.send("You called /api/ping");
});
to
router.get('/', function (req, res) {
res.send("You called /api/ping");
});
I think your routing is incorrect on this line
router.use('/ping', require('./ping'));
this will point to http/api/ping/ping
it should be
router.use('/', require('./ping'));

Node.js Express export routes for organization?

Utilizing express.Router() for API calls to/from our application:
var express = require('express');
var app = express();
var router = express.Router();
router.use console.logs before every API call:
router.use(function(req, res, next) { // run for any & all requests
console.log("Connection to the API.."); // set up logging for every API call
next(); // ..to the next routes from here..
});
How do we export our routes to folder/routes.js and access them from our main app.js, where they are currently located:
router.route('/This') // on routes for /This
// post a new This (accessed by POST # http://localhost:8888/api/v1/This)
.post(function(req, res) {
// do stuff
});
router.route('/That') // on routes for /That
// post a new That (accessed by POST # http://localhost:8888/api/v1/That)
.post(function(req, res) {
// do stuff
});
...when we prefix every route with:
app.use('/api/v1', router); // all of the API routes are prefixed with '/api' version '/v1'
In your new routes module (eg in api/myroutes.js), export the module.
var express = require('express');
var router = express.Router();
router.use(function(req, res, next) {
console.log('Connection to the API..');
next();
});
router.route('/example')
.get(function(req, res) { });
.post(function(req, res) { });
module.exports = router;
Then you can require the module in your main server/app file:
var express = require('express');
var app = express();
var myRoutes = require('./api/myRoutes');
app.use('/api', myRoutes); //register the routes
In your app.js file you can have the following:
//api
app.use('/', require('./api'));
In the folder api you can have 'index.js` file, where you can write something like this:
var express = require('express');
var router = express.Router();
//API version 1
router.use('/api/v1', require('./v1'));
module.exports = router;
In the folder v1 file index.js something like this:
var express = require('express');
var router = express.Router();
router.use('/route1', require('./route1'));
router.use('/route2', require('./route2'));
module.exports = router;
File route1.js can have the following structure:
var express = require('express');
var router = express.Router();
router.route('/')
.get(getRouteHandler)
.post(postRouteHandler);
function getRouteHandler(req, res) {
//handle GET route here
}
function postRouteHandler(req, res) {
//handle POST route here
}
module.exports = router;
route2.js file can have the same structure.
I think this is very comfortable for developing the node project.

Categories

Resources