Express.JS GET API call returns 500
I created a GET API call intended to fetch every user in my Logins database. For some reason, I keep on getting 500 calls on it. Here is my code:
const http = axios.create({
baseURL: "http://localhost:8080/api",
headers: {
"Content-type": "application/json"
}
});
function fetchUsers(){
http.get("/getusers").catch(err => {
console.log("OOF: " + err.message);
});
}
fetchUsers();
This is the routes file:
const users = require("../controller/users.controller.js");
var express = require('express');
var router = express.Router();
const pathStart = "/api";
// Retrieve all Users
router.get(pathStart + "/getusers", users.findAll);
My routes file is being used in my app.js file:
var indexRouter = require('./routes');
var userRouter = require('./routes/users.routes.js');
var app = express();
app.use('/', indexRouter);
app.use('/', userRouter);
users.controller.js:
// Retrieve all users from the database.
exports.findAll = (req, res) => {
console.log("extracting users");
const user = req.query.user;
var condition = user ? { user: { [Op.like]: `%${user}%` } } : null;
Users.findAll({ where: condition })
.then(data => {
res.send(data);
})
.catch(err => {
res.status(500).send({
message: err.message || "Error occurred when retrieving users"
})
});
};
This is my output: OOF: Request failed with status code 500
It is because of these two lines :
app.use('/', indexRouter);
app.use('/', userRouter);
Basically you will never enter inside useRouter, the first one catches every request. You need to have something like this :
In app.js
app.use('/api/user/', userRouter);
app.use('/', indexRouter);
In user router
const users = require("../controller/users.controller.js");
var express = require('express');
var router = express.Router();
// const pathStart = "/api"; not needed anymore
// Retrieve all Users
router.get("/getusers", users.findAll);
Your fetch logic :
const http = axios.create({
baseURL: "http://localhost:8080/api",
headers: {
"Content-type": "application/json"
}
});
function fetchUsers(){
http.get("/user/getusers").catch(err => {
console.log("OOF: " + err.message);
});
}
fetchUsers();