ES6 Dynamic Module Import Express Routes - node.js

I'm attempting to dynamically import files containing routes for an Express server using ES6 notation instead of associating each route with a file like this:
import router from './routes/test.mjs'
app.use('/api/create/test', router)
In my main file App.js I have a function which aims to return the matching :entity import from the query parameters:
async function routingFunct(req, res, next){
let entity=req.params.entity
const { default: dynamicImport } = await import(`./routes/${entity}.mjs`);
return dynamicImport
}
app.use('/api/create/:entity', routingFunct)
In my ./routes/test.mjs file I have
router.get('/', async function(req, res)
{
...await logic here...
})
export default router
When sending a get request to the endpoint /api/create/test, the page simply hangs forever. What am I doing wrong here? How can I tell my Express server to run the middleware in App.js then run the logic in the matching :entity.mjs?

Related

Routes are not working in my express js app

I was working on a personal express project. I've created two files one server file and other restaurants.route.js to sepearate routes and server code. But I'm not able trigger the home route from local host. Moreover no console error is showing only the 404 page error.
server.js code:
import express from "express";
import cors from "cors";
import restaurants from "./api/restaurants.route.js";
// initialising express app
const app = express();
// applying middlewears
app.use(cors());
app.use(express.json());
app.use("api/v1/restaurants", restaurants);
app.use("*", (req, res) => res.status(404).json({error: "not found"}));
export default app;
restaurants.route.js:
import express from "express";
// express router
const router = express.Router();
router.route("/")
.get((req, res) => {
res.send("Hello World");
});`enter code here`
export default router;
It looks like you might be missing the leading forward slash (/) in the path you're using to mount the restaurants router in your server.js file. When you use the app.use() method to mount a router, the path you specify should start with a forward slash.
So instead of this:
app.use("api/v1/restaurants", restaurants);
Try this:
app.use("/api/v1/restaurants", restaurants);

Accessing request middleware from inside models

When we setup a Node Express application, by default the main app.js file is created and two routes (index.js and users.js). The request middleware can be directly accessed from inside the routes folder.
//routes/index.js
const user = require('../models/users.js');
const createUser = user.createUser;
router.post('/signup', async (req, res, next) => {
await craeteUser(req);
...
//I can get req.body.anything
})
Is there any way to access the reuest body inside models folder. (say) I have created a users model that has a function like this...
//models/users.js
async function createUser(req)
{
....
//I cannot get req.body.anything
}
module.exports = {createUser}

404 when trying to get response from backend using axios

I am trying to get function result from backend to frontend via axios but it returns 404 every time.
I managed to send request to backend and activate function but on geting result it started returning 404
route in app.ts
import cardRoute from './routes/test';
const app = express();
app.use('/test', cardRoute);
./routes/test.ts (backend)
function test_load() returns string
import express from 'express';
import { test_load } from '../cardpull';
const router = express.Router();
router.post('./test-bed',
async (req, res) => {
let cards = test_load()
res.send(cards);
},
);
export default router;
Frontend call
async function GetCard() {
var cards = await axios.post<string>('/test/test-bed');
return cards;
};
your route is not valid
router.post('./test-bed',
async (req, res) => {
let cards = test_load()
res.send(cards);
},
);
should be:
router.post('/test-bed',
async (req, res) => {
let cards = test_load()
res.send(cards);
},
);
and on your axios URL, maybe you need to include the host and port because if you define only the endpoint, it will hit your frontend host and port,
example if you open express on localhost:3000
then the axios will be
axios.post('http://localhost:3000/test/test-bed')
note: I didn't write the answer with typescript, but with javascript style should be clear enough.

How to import all express routes defined in different files using `import`

Folder structure
index.js
modules/users/users.server.routes.js
modules/users/users.server.routes.js
export default (app) => {
app.route('/api', (req, res) => {
res.send('User routes working');
});
};
index.js
import express from 'express';
import mongoose from 'mongoose';
/*
* For iterating through files using a regex
* */
import glob from 'glob';
let files = glob.sync('app/**/*.routes.js');
files = files.map((file) => {
import(file);
});
const app = express();
const config = {
app_port: 8080
};
/*
* Test route
* */
app.get('/', (req, res) => {
res.send('Voila!!');
});
Above code is giving an error!
'import' and 'export' may only appear at the top level
What I want to achieve is, once the server gets started, all the routes should be imported. (Live require(--route file--))
I don't want to declare all the routes in a single routes file like this.
// mount user routes at /users
router.use('/users', userRoutes);
// mount auth routes at /auth
router.use('/auth', authRoutes);
I want each route to be defined from the root of the API.
How to achieve this in ES6 way?
Thank you all!

Express: how can I get the app from the router?

I know I can get the Express app from inside an individual route with:
req.app
However I need to start a single instance of a module inside routes/index.js, i.e.:
var myModule = require('my-module')(propertyOfApp)
How can I get the express app from the router?
It really depends on your own implementation, but what I suggested in the comments should be working:
// index.js
module.exports = function(app) {
// can use app here
// somehow create your router and do the magic, configure it as you wish
router.get('/path', function (req, res, next) {});
return router;
}
// app.js
// actually call the function that is returned by require,
// and when executed, the function will return your configured router
app.use(require('./index')(app));
p.s.
Of course this is just a sample - you can configure your router with path, and all kind of properties you wish. Cheers! :)

Resources