I've been working on accessing data from my custom REST API, but I'm encountering an issue where the JSON data is not being displayed when I navigate to the endpoints. I have set up server, controller, and data controller classes in order to create and configure the API. The server and controllers load properly, however, when I visit an endpoint, it only shows the default React app page.
Here is the method for loading controllers in the server:
public loadControllers(controllers: Array<Controller>): void {
controllers.forEach(controller => {
console.log(controller, controller.path)
this.app.use(controller.path, controller.setRoutes());
});
};
And here is the method for setting routes in the controller:
public setRoutes = (): Router => {
for (const route of this.routes) {
for (const mw of route.localMiddleware) {
this.router.use(route.path, mw)
};
switch (route.method) {
case Methods.GET:
this.router.get(route.path, route.handler);
break;
case Methods.POST:
this.router.post(route.path, route.handler);
break;
case Methods.PUT:
this.router.put(route.path, route.handler);
break;
case Methods.DELETE:
this.router.delete(route.path, route.handler);
break;
default:
console.log('not a valid method')
break;
};
};
return this.router;
}
This is an example route and handler in the DataController:
routes = [
{
path: '/locations',
method: Methods.GET,
handler: this.handleGetLocations,
localMiddleware: [],
},
]
async handleGetLocations (req: Request, res: Response, next: NextFunction, id?: number) {
try{
this.dbConn.initConnectionPool()
.then((pool) => {
pool.query(`query here`)
})
.then((data) => {
res.send(data);
})
}
catch(err){
console.log(err);
}
}
Even though everything seems to be correct when logged in the console, the JSON data is still not displaying at the endpoints.