Problem
I'm creating a Node.js Rest APIs with Express, Sequelize, Sequelize-cli and MySQL, but when I tested it with a Post request, the one creating a new user, on Postman I always got a 500 Internal Server Error.
Trials
I tried with a GET request, to see if I could get the data about a previously created user, but I again get a 500 Internal Server Error.
I already checked my database, but everything is ok there. There is both my database and the tables as you can see here.
And I also checked that the connection with the database was established trough:
sequelize.authenticate().then(()=>{
console.log('Connection has been established successfully!');
}).catch (error =>{
console.error('Unable to connect to the database!');
});
I also checked my routes, controllers, and package to see if I forgot a dependency or something, but I found no problem :/.
Code
Here is my code:
At the root of the project:
server.js
const express = require("express");
const cors = require("cors");
const userRoutes = require("./routes/user.routes.js");
const app = express();
var corsOptions = {
origin: "http://localhost:8081"
};
app.use(cors(corsOptions));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use((req, res, next) => {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content, Accept, Content-Type, Authorization');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, PATCH, OPTIONS');
next();
});
app.use('/api/users', userRoutes);
const PORT = 8080;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}.`);
});
From there, I used Sequelize-CLI to create a user model in models folders:
user.js
'use strict';
/** @type {import('sequelize-cli').Migration} */
module.exports = {
async up(queryInterface, Sequelize) {
await queryInterface.createTable('users', {
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: Sequelize.INTEGER
},
firstName: {
type: Sequelize.STRING
},
lastName: {
type: Sequelize.STRING
},
email: {
type: Sequelize.STRING
},
password: {
type: Sequelize.STRING
},
createdAt: {
allowNull: false,
type: Sequelize.DATE
},
updatedAt: {
allowNull: false,
type: Sequelize.DATE
}
});
},
async down(queryInterface, Sequelize) {
await queryInterface.dropTable('users');
}
};
Then, I created his controllers and its routes, respectively in the controllers and routes folders:
user.controller.js
const user = require("../models/user.js");
const Sequelize = require("../models/index.js");
const Op = Sequelize.Op;
let self = {};
self.createUser = async (req, res) => {
if (!req.body.firstName || !req.body.lastName) {
res.status(400).send({
success: false,
message: "Content can not be empty!"
});
return;
}
try {
const newUser = {
firstName: req.body.firstName,
lastName: req.body.lastName,
email: req.body.email,
password: req.body.password
};
let data = await user.create(newUser);
return res.status(201).json({
success: true,
data: data
})
} catch (error) {
return res.status(500).json({
success: false,
error: error
})
}
}
self.get = async (req, res) => {
try {
let id = req.params.id;
let data = await user.findByPk(id,
{
where: {
id: id
},
include: [{
model: project,
as: 'projects'
}]
}
);
if (data)
return res.status(200).json({
success: true,
data: data
})
else
return res.status(200).json({
success: false,
error: "No such user present",
data: []
})
} catch (error) {
res.status(500).json({
success: false,
error: error
})
}
}
module.exports = self;
user.routes.js
const user = require("../controllers/user.controller.js");
const router = require("express").Router();
router.get('/', user.getAll);
router.get('/:id', user.get);
router.post('/', user.createUser);
router.put('/:id', user.updateUser);
router.delete('/:id', user.delete);
router.delete('/', user.deleteAll);
module.exports = router;
By the way, there is also the config.json
in the config folder:
{
"development": {
"username": "root",
"password": "MhSyLoPoLoMY8Hg&",
"database": "groupomania",
"host": "localhost",
"dialect": "mysql"
},
"test": {
"username": "root",
"password": null,
"database": "database_test",
"host": "127.0.0.1",
"dialect": "mysql"
},
"production": {
"username": "root",
"password": null,
"database": "database_production",
"host": "127.0.0.1",
"dialect": "mysql"
}
}
Here's the log statement
of the 500 internal error:
POST http://localhost:8080/api/users
500
8 ms
POST /api/users HTTP/1.1
Content-Type: application/json
User-Agent: PostmanRuntime/7.32.3
Accept: */*
Postman-Token: 6d67840d-fa40-46ca-9849-ec2847236d19
Host: localhost:8080
Accept-Encoding: gzip, deflate, br
Connection: keep-alive
Content-Length: 131
{
"firstName": "testfirstName",
"lastName": "testlastName",
"email": "testemail",
"password": "passwordpassword"
}
HTTP/1.1 500 Internal Server Error
X-Powered-By: Express
Access-Control-Allow-Origin: *
Vary: Origin
Access-Control-Allow-Headers: Origin, X-Requested-With, Content, Accept, Content-Type, Authorization
Access-Control-Allow-Methods: GET, POST, PUT, DELETE, PATCH, OPTIONS
Content-Type: application/json; charset=utf-8
Content-Length: 28
ETag: W/"1c-9j3+7zIZYFzBJCw8ZKi1q8+V98A"
Date: Sun, 25 Jun 2023 16:09:47 GMT
Connection: keep-alive
Keep-Alive: timeout=5
{"success":false,"error":{}}
Thank you in advance for any help someone can offer me.
P.S: Here is my project repository, if you need to see more :D. Or just ask me, I will do my best to answer you :).
In user.controller.js
:
const { user, Sequelize, project } = require("../models");
user
and project
are all undefined here. Check the models/index.js, export user
and project
correctly.
p.s. I suggest you to learn how to debug nodejs using nodemon, so you can figure out the reason of most problems by yourself: How to debug application using nodemon in nodeJs