Express - set routes in one routes - javascript

index.js
app.use('/',wowYeah);
app.use('/lol',wow);
how to use only
routes.js
app.use('/',wowYeah);
app.use('/lol',wow);
app.use(routes());
but it can't
how to do it?
1 app use for all routes

// birds.js file
const express = require('express')
const router = express.Router()
// middleware that is specific to this router
router.use(function timeLog (req, res, next) {
console.log('Time: ', Date.now())
next()
})
// define the home page route
router.get('/', function (req, res) {
res.send('Birds home page')
})
// define the about route
router.get('/about', function (req, res) {
res.send('About birds')
})
module.exports = router
// index.js file
const birds = require('./birds')
// ...
app.use(birds)
for more look documentation.

Related

Node.js expressjs Nested Routes ,

index.js
const AuthRouter = require("./Routes/Auth/signup")
app.use("/account", AuthRouter)
signup.js
router.post("/", async (req, res) => {
res.send("Signup")
})
This Code works...
But I won't like this, It's Possible in Express.js
index.js
const AuthRouter = require("./Routes/Auth/urls")
app.use("/account", AuthRouter)
urls.js
app.use("/signup", signup)
app.use("/login", login)
signup.js
router.post("/", async (req, res) => {
res.send("Signup")
})
login.js
router.post("/", async (req, res) => {
res.send("Login")
})
You could do it inline as well. I prefer it that way. like this on the server:
app.use('/users', require('../utils/api/user'))
And the route file like this called user.js in the given directory:
const express = require('express')
const router = express.Router()
router.post('/login', (req, res) => {
res.render('user', {title: 'User', user})
})
router.post('/signup', (req, res) => {
res.render('user', {title: 'User', user})
}
module.exports = router
Now the route on client side to login is /users/login and to signup is /users/signup
Yes, you can do that.
For instance, you will have to dedicate a specific file for your routes. Say routes.js like this:
import express from "express";
import { Signup } from "./";
const router = express.Router();
router.post("/signup", signup);
export { router }
Also, you have to have something like this in your server.js file:
import { router as usersRoutes } from "./api/routes/routes";
app.use("/api", usersRoutes);
Now, you can send HTTP POST requests to localhost:3000/api/signup

Route requiring a middleware function

I'm creating my routes module in nodejs with socket.io
var express = require("express"); // call express
var taskSchema = require("../models/taskModel");
var mongoose = require("mongoose");
var router = express.Router(); // get an instance of the express Router
module.exports = function (io) {
router.use(function (req, res, next) {
io.sockets.emit('payload');
console.log("Something is happening.");
next();
});
router
.route("/tasks")
.post(function (req, res, next) {
...
});
router
.route("/tasks")
.get(function (req, res) {
...
});
};
When I compile server I get this error
TypeError: Router.use() requires a middleware function but got a undefined
It appears to me that the problem is probably in the code that loads this module because you never export the actual router. So, assuming you do app.use() or router.use() in the caller who loads this module, your aren't returning the router from your function so there's no way to hook that router in and you would get the error you see.
I'm guessing that you can fix this by just returning the router from your exported function:
var express = require("express"); // call express
var taskSchema = require("../models/taskModel");
var mongoose = require("mongoose");
var router = express.Router(); // get an instance of the express Router
module.exports = function (io) {
router.use(function (req, res, next) {
io.sockets.emit('payload');
console.log("Something is happening.");
next();
});
router
.route("/tasks")
.post(function (req, res, next) {
...
});
router
.route("/tasks")
.get(function (req, res) {
...
});
return router; // <=========== Add this
};
Then, when you do:
let m = require('yourModule');
router.use(m(io));
Then function will return the router that router.use() will be happy with. You can pass either middleware or a router to .use().
If this guess isn't quite on target, then please show us the code that loads and calls this module.
When that function is called it's gonna return the equivalent of undefined. Also, normally a route is defined before the endpoint. It's typically structured like:
let myRouter = new Router();
Router.use('something', middlewareFunction, someotherprocess);

express.js - single routing handler for multiple routes

I'm currently building an app and I have a routes file that looks like this.
const router = require('express').Router();
router.get('/', (req, res) => res.render('statics/home'));
router.get('/jobs', (req, res) => res.render('statics/jobs'));
router.get('/about-page', (req, res) => res.render('statics/about-page'));
router.get('/valves', (req, res) => res.render('statics/valves'));
router.all('*', (req, res) => res.notFound());
module.exports = router;
I am trying to figure out a way to refactor my routes and have a single route that accepts any string and then checks to see if a file exists matching it
Any help appreciated!
To easily handle static file, you can use express static, express will automatic route all file inside static folder
app = require('express')();
app.use('statics',express.static('statics'));
Something like this could work:
const router = require('express').Router();
const fs = require('fs');
router.get(':template', (req, res) => {
const tpl = req.param('template');
if (tpl) {
if (fs.existsSync('/path/to/templates/' + tpl + '.ext')) { // adjust the path and template extension
res.render('statics/' + tpl);
} else {
res.notFound();
}
} else {
res.render('statics/home');
}
});
router.all('*', (req, res) => res.notFound());
module.exports = router;
Or probably better approach would be to read the templates directory once and create routes based on its contents:
const router = require('express').Router();
const fs = require('fs');
const templates = fs.readdirSync('/path/to/templates');
templates.forEach(tpl => {
tpl = tpl.substring(tpl.lastIndexOf('/') + 1);
if (tpl === 'home') {
router.get('/', (req, res) => res.render('statics/home'))
} else {
router.get('/' + tpl, (req, res) => res.render('statics/' + tpl))
}
});
router.all('*', (req, res) => res.notFound());
module.exports = router;

Separating Express.js-Routes into separate Files

I'm using express.js and am trying to separate my routes in a separate file.
This is an excerpt from my ./app.coffee:
viewsRouter = express.Router()
routesCallingViews = require('./app/routes/callingViews')
app.use '/', routesCallingViews.showApp viewsRouter, user, data
app.use '/', routesCallingViews.showSignUpForm viewsRouter
app.use '/', routesCallingViews.showLogInForm viewsRouter
the ./app/routes/callingViews looks like:
module.exports =
showApp: (router, user, data) ->
router.get '/', user.isSignedIn, (req, res) ->
...
showSignUpForm: (router) ->
router.get '/signup', (req, res) ->
...
showLogInForm: (router) ->
router.get '/login', (req, res) ->
...
I get this error:
Error: Route.get() requires callback functions but got a [object Undefined]
Any suggestions?
Common way to do what you are trying would be to extract all related routes to separate module where you would create and export instance of router, something like:
// foo.js
'use strict'
const express = require('express')
const router = express.Router()
router.get('/', (req, res, next) => { ... })
router.post('/bar', (req, res, next) => { ... })
...
module.exports = router
Then from whatever place (usually from server.js) you would hook all routers that you have, something like:
const fooRoutes = require('./foo')
app.use('/foo', fooRoutes)
So you will end up with:
GET /foo
POST /foo/bar

NodeJS Routing issue

how can I route below url to different view in node.js
http://admin.localhost:3000/users/customer/view
and
http://localhost:3000/users/customer/view
currently it go to the same route that I set for
http://localhost:3000/users/customer/view
App.js
....
var users = require('./routes/users');
app.use('/users', users);
....
Users.js
var express = require('express');
var router = express.Router();
/* GET users listing. */
router.get('/', function(req, res, next) {
res.send('respond with a resource');
});
router.get('/Customer/Create', function(req, res, next) {
res.render('customer', {});
});
router.get('/Customer/View', function(req, res, next) {
res.render('customer', {});
});
router.get('/Employee/Create', function(req, res, next) {
res.render('customer', {});
});
router.get('/Employee/View', function(req, res, next) {
res.render('customer', {});
});
module.exports = router;
and what is the terminology for doing something like this with your url by adding admin before url admin.yoururl.com ?
Since you are using express, you can use the express middleware express-subdomain.
The package even supports multi level subdomains like v1.api.domain.com.
You need to create one Router per subdomain and then bind that Router to your express app using the package:
var subdomain = require('express-subdomain');
var express = require('express');
var app = express();
var router = express.Router();
//api specific routes
router.get('/', function(req, res) {
res.send('Welcome to our API!');
});
router.get('/users', function(req, res) {
res.json([
{ name: "Brian" }
]);
});
app.use(subdomain('api', router));
app.listen(3000);

Categories

Resources