Reputation: 13771
does anyone know of a way I can read the contents of my express route? For example, suppose I have a route like:
router.post('/test', (req, res) => {
let postBody = {
firstName: {
required: true,
description: "First Name"
},
lastName: {
required: true,
description: "Last Name"
},
email: {
required: true,
description: "Your email"
}
}
res.json({
msg: "Success"
})
})
My objective is to read the contents of postBody
for each route when the app starts.
My app.js
:
import express from 'express'
const router = express.Router()
const app = express()
app._router.stack.forEach(middleware => {
if (middleware.handle && middleware.handle.stack) {
middleware.handle.stack.forEach(route => {
console.log(route)
})
}
})
app.use(router)
Using the above code, I can print out all of my routes. However, I am looking to print out the postBody
of each route when the app starts. Can someone help?
Thanks in advance!
Upvotes: 0
Views: 52
Reputation: 5259
The place that you have kept postBody variable is only executed when those routes are hit. To read them outside of those call backs you should be able to pass them into a common module. In my sample below I call it "postBodies". Every route passes its postBody into this module and as the last entry in the bottom of your main app.js file I call readAll() to print out all the internally stored postBody values up to that point.
const postBodies = require("./postBodies.js")
router.post('/test', (req, res) => {
let postBody = {
firstName: {
required: true,
description: "First Name"
},
lastName: {
required: true,
description: "Last Name"
},
email: {
required: true,
description: "Your email"
}
}
postBodies.update(postBody)
res.json({
msg: "Success"
})
})
postBodies.js
var bodies[]
module.exports.update = function(x){
bodies.push(x)
}
module.exports.readAll = function(){
bodies.forEach(function(x){
console.log(x)
}
}
app.js or index.js
At the very bottom after all your route calls.
postBodies.readAll()
Upvotes: 1