英文:
CRUD API - 500 Internal Server Error with Postman
问题
问题
我正在使用Express、Sequelize、Sequelize-cli和MySQL创建Node.js Rest APIs,但是当我在Postman中测试它时,使用[Post请求][1]创建新用户时,我总是收到500内部服务器错误。
尝试
我尝试了[GET请求][2],以查看是否可以获取以前创建的用户的数据,但我再次收到500内部服务器错误。
我已经检查了我的数据库,但那里的一切都没问题。你可以在[这里][3]看到我的数据库和表。
我还检查了与数据库的连接是否通过以下方式建立:
sequelize.authenticate().then(() => {
console.log('Connection has been established successfully!');
}).catch(error => {
console.error('Unable to connect to the database!');
});
[![与数据库建立连接][4]][4]
我还检查了我的路由、控制器和包,看看是否忘记了依赖项或其他问题,但我没有找到问题 :/。
代码
以下是我的代码:
在项目的根目录:
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}.`);
});
然后,我使用Sequelize-CLI在models文件夹中创建了一个用户模型:
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');
}
};
然后,我在controllers和routes文件夹中分别创建了控制器和路由:
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;
顺便说一下,在config文件夹中也有config.json
:
{
"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"
}
}
这是500内部错误的日志语句
:
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+7zIZ
<details>
<summary>英文:</summary>
**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][1], the one creating a new user, on Postman I always got a 500 Internal Server Error.
**Trials**
I tried with a [GET request][2], 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][3].
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!');
});
[![Connection with database established][4]][4]
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][5], if you need to see more :D. Or just ask me, I will do my best to answer you :).
[1]: https://i.stack.imgur.com/WpzIj.png
[2]: https://i.stack.imgur.com/C0ux3.png
[3]: https://i.stack.imgur.com/QPjf1.png
[4]: https://i.stack.imgur.com/iqF2Q.png
[5]: https://github.com/RayanBarbara/backend
</details>
# 答案1
**得分**: 0
在 `user.controller.js` 文件中:
```javascript
const { user, Sequelize, project } = require("../models");
在这里,user
和 project
都未定义。请检查 models/index.js
文件,确保正确导出了 user
和 project
。
附言:
我建议您学习如何使用 nodemon 调试 Node.js,这样您可以自己找出大多数问题的原因:https://stackoverflow.com/questions/36262620/how-to-debug-application-using-nodemon-in-nodejs
英文:
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: https://stackoverflow.com/questions/36262620/how-to-debug-application-using-nodemon-in-nodejs
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论