Say I have file1.js:
import Router from "express-promise-router";
export const router1 = Router();
router1.get("/", async (req, res) => {
// I want to get here :id from router2 in file2
})
And file2.js (in the same directory for simplicity):
import Router from "express-promise-router";
import { router1 } from "./file1";
export const router2 = Router();
router2.use("/:id/path", router1);
I want to use /:id from file2.js in file1.js (see my comment in example code).
How can I do that?
In other words, how can I percolate '/:something' parameter down the routers chain?
Note - this doesn't work:
router1.get("/", async (req, res) => {
const { params: {id} } = req;
})
I found the answer.
From express api:
So should add the option mergeParams set to true when declaring the router handler.
In general:
const router = express.Router({mergeParams: true});.
For the question's example code in file1.js:
import Router from "express-promise-router";
export const router1 = Router({mergeParams: true});
router1.get("/", async (req, res) => {
const { params: {id} } = req; // now this works
})
Related
I am working on creating the classical car API. Now I'm trying to pull a JSON Array from an external file.
I made a step toward a resolution, however my "solution" will return the full object, instead of the array json.
This is from the vehicles.js file, found under api/routes/
import express from 'express';
import path from 'path';
import { fileURLToPath } from 'url';
import { dirname } from 'path';
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
const router = express.Router();
router.get('/', (req, res, next) => {
res.status(200).sendFile(path.join(__dirname, '../resources', 'vehicles.json'));
});
export default router;
The app.js looks like this:
import express from 'express';
const app = express();
import vehiclesRoute from './api/routes/vehicles.js';
app.use('/vehicles', vehiclesRoute);
export default app;
Something else I tried was in the lines of:
import parsedJSON from './resources/vehicles.json';
var vehiclesJSON = parsedJSON.vehicles;
router.get('/', (req, res, next) => {
let vehiclesJSONpath = path.join(__dirname, '../resources', 'vehicles.json');
res.status(200).fetch(vehiclesJSONpath)
.then(res => res.json())
.then(data => console.log(data));
});
Is there a way I can do the parsing and include it in the response body of the callback?
Is there maybe a route I need to configure anew, so that the array can be simply extracted?
Thanks!
Will close this. The solution was simple.
'use strict';
let rawdata = fs.readFileSync('api/resources/vehicles.json');
let vehicles = JSON.parse(rawdata);
Then, in order to be able to get it as a response:
router.get('/', (req, res, next) => {
res.status(200).json(vehicles);
});
Saved by: https://stackabuse.com/reading-and-writing-json-files-with-node-js/
I am trying to change my routers into class but I don't know how to wrap the asyncHandler in function inside the class
userController.js
const asyncHandler = require('express-async-handler')
class UserController {
async Register(req, res){
const {firstName} = req.body
return res.status(200).send(firstName)
}
}
const userController = new UserController()
module.exports = userController
userRouter.js
const express = require('express')
const userController = require('../controllers/userController')
const router = express.Router()
router.post('/register', userController.Register)
module.exports = router
You can actually use asyncHandler like this,
As per the docs
router.post('/register', asyncHandler(userController.Register))
I'm trying to implement a dynamic import inside a express.js router
now I have a bellow code
HelloWorldController.js
export const helloWorld = function (req, res) {
res.send('hello world')
}
router.js
export default async function (app) {
app.use('/', await ( async function () {
const helloWorldController = await import('./helloWorldController.js')
const router: express.Router = express.Router()
router
.get('/', helloWorldController.helloWorld)
return router
})
}
server.js
import express from 'express'
import router from './router.js'
const app = express()
router(app)
app.listen(3000, function(){
logger.ready(`Web Server is running on port 3000`)
})
This is the result I'm getting when I run server.js
I have a 404 error
GET / 404 18.761 ms - 25
This is working fine
router.js
import * as helloWorldController './helloWorldController.js'
export default async function (app) {
app.use('/', await ( async function () {
const router: express.Router = express.Router()
router
.get('/', helloWorldController.helloWorld)
return router
})
}
** What am I doing wrong? **
ES6 import syntax is not supported yet in node js,
try this syntax const {express} = require("express")
I'm using Koa.js and I was wondering how I could use a middleware with router.verb()
As mentioned here router.use([path], middleware) I tried like below.
The console.log() trigger but the users.list is not called
My main objective is to do an auth middleware
const Router = require("#koa/router");
const router = new Router();
const users = require("./Controllers/users/index.js");
router.use("/user", (ctx, next) => {
console.log(ctx);
next();
});
router.get("/user", users.list)
I don't get any error messages but the users.list don't execute.
Then i tried this
router.get("/user", (ctx, next) => {
console.log(ctx);
next();
}, users.list)
But i don't get any change and I feel like I don't understand something, but can't figure out what
In my index.js
const Koa = require("koa");
const router = require("./Routes");
const bodyParser = require("koa-bodyparser");
const cors = require("#koa/cors");
const serve = require("koa-static");
const path = require("path");
const errorHandler = require("./Middlewares/errorHandler");
const app = new Koa();
app.use(errorHandler)
.use(bodyParser())
.use(cors())
.use(router.routes())
.use(serve(path.join("public", "ads")))
.use(router.allowedMethods());
in my controller
const { Users } = require("../../Models");
module.exports = {
list: async (ctx, next) => {
let AllUsers = await Users.findAll();
ctx.body = AllUsers;
}
}
I got it working with adding await next()
router.use("/ads", async (ctx, next) => {
console.log(ctx);
await next();
});
Since my controller is an async function I get my explanations from here -> async/await always returns promise
I have checked many answers in other pages and forums, but I still don't get it. What did I do wrong? Help me
*edited. I have added requiring routes and app.use. It looks like function isLOggedIn is not exporting but I don't know how to do that. I did like this in another app, it worked there.
auth-routes.js
const express = require("express"),
router = express.Router(),
passport = require("passport")
function isLoggedIn(req, res, next) {
if (req.isAuthenticated()) {
return next()
}
res.redirect("/auth/login")
}
module.exports = router
user-routes.js
const express = require("express"),
router = express.Router(),
authRoutes = require("./auth-routes")
router.get("/profile", authRoutes.isLoggedIn, (req, res) => {
res.render("user/profile", {user: req.user})
})
module.exports = router
requring routes
const titleRoutes = require("./routes/title-routes")
const authRoutes = require("./routes/auth-routes")
const userRoutes = require("./routes/user-routes")
app.use
app.use(titleRoutes)
app.use("/auth", authRoutes)
app.use("/user", userRoutes)
In auth-routes.js you don't export isLoggedIn. So in user-routes.js, authRoutes.isLoggedIn is undefined.
You can change:
module.exports = router
into:
exports.isLoggedIn = isLoggedIn
or using module.exports into:
module.exports = { isLoggedIn: isLoggedIn }
A useful link to understand export in nodejs https://www.sitepoint.com/understanding-module-exports-exports-node-js/