CRUD API – Postman 中的 500 内部服务器错误

huangapple go评论83阅读模式
英文:

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&#39;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(()=&gt;{
console.log(&#39;Connection has been established successfully!&#39;);
}).catch (error =&gt;{
console.error(&#39;Unable to connect to the database!&#39;);
});
[![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(&quot;express&quot;);
const cors = require(&quot;cors&quot;);
const userRoutes = require(&quot;./routes/user.routes.js&quot;);
const app = express();
var corsOptions = {
origin: &quot;http://localhost:8081&quot;
};
app.use(cors(corsOptions));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use((req, res, next) =&gt; {
res.setHeader(&#39;Access-Control-Allow-Origin&#39;, &#39;*&#39;);
res.setHeader(&#39;Access-Control-Allow-Headers&#39;, &#39;Origin, X-Requested-With, Content, Accept, Content-Type, Authorization&#39;);
res.setHeader(&#39;Access-Control-Allow-Methods&#39;, &#39;GET, POST, PUT, DELETE, PATCH, OPTIONS&#39;);
next();
});
app.use(&#39;/api/users&#39;, userRoutes);
const PORT = 8080;
app.listen(PORT, () =&gt; {
console.log(`Server is running on port ${PORT}.`);
});
From there, I used Sequelize-CLI to create a user model in models folders:
`user.js`
&#39;use strict&#39;;
/** @type {import(&#39;sequelize-cli&#39;).Migration} */
module.exports = {
async up(queryInterface, Sequelize) {
await queryInterface.createTable(&#39;users&#39;, {
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(&#39;users&#39;);
}
};
Then, I created his controllers and its routes, respectively in the controllers and routes folders:
`user.controller.js`
const  user = require(&quot;../models/user.js&quot;);
const Sequelize = require(&quot;../models/index.js&quot;);
const Op = Sequelize.Op;
let self = {};
self.createUser = async (req, res) =&gt; {
if (!req.body.firstName || !req.body.lastName) {
res.status(400).send({
success: false,
message: &quot;Content can not be empty!&quot;
});
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) =&gt; {
try {
let id = req.params.id;
let data = await user.findByPk(id,
{
where: {
id: id
},
include: [{
model: project,
as: &#39;projects&#39;
}]
}
);
if (data)
return res.status(200).json({
success: true,
data: data
})
else
return res.status(200).json({
success: false,
error: &quot;No such user present&quot;,
data: []
})
} catch (error) {
res.status(500).json({
success: false,
error: error
})
}
}
module.exports = self;
`user.routes.js`
const user = require(&quot;../controllers/user.controller.js&quot;);
const router = require(&quot;express&quot;).Router();
router.get(&#39;/&#39;, user.getAll);
router.get(&#39;/:id&#39;, user.get);
router.post(&#39;/&#39;, user.createUser);
router.put(&#39;/:id&#39;, user.updateUser);
router.delete(&#39;/:id&#39;, user.delete);
router.delete(&#39;/&#39;, user.deleteAll);
module.exports = router;
By the way, there is also the `config.json` in the config folder:
{
&quot;development&quot;: {
&quot;username&quot;: &quot;root&quot;,
&quot;password&quot;: &quot;MhSyLoPoLoMY8Hg&amp;&quot;,
&quot;database&quot;: &quot;groupomania&quot;,
&quot;host&quot;: &quot;localhost&quot;,
&quot;dialect&quot;: &quot;mysql&quot;
},
&quot;test&quot;: {
&quot;username&quot;: &quot;root&quot;,
&quot;password&quot;: null,
&quot;database&quot;: &quot;database_test&quot;,
&quot;host&quot;: &quot;127.0.0.1&quot;,
&quot;dialect&quot;: &quot;mysql&quot;
},
&quot;production&quot;: {
&quot;username&quot;: &quot;root&quot;,
&quot;password&quot;: null,
&quot;database&quot;: &quot;database_production&quot;,
&quot;host&quot;: &quot;127.0.0.1&quot;,
&quot;dialect&quot;: &quot;mysql&quot;
}
}
Here&#39;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
{
&quot;firstName&quot;: &quot;testfirstName&quot;,
&quot;lastName&quot;: &quot;testlastName&quot;,
&quot;email&quot;: &quot;testemail&quot;,
&quot;password&quot;: &quot;passwordpassword&quot;
}
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/&quot;1c-9j3+7zIZYFzBJCw8ZKi1q8+V98A&quot;
Date: Sun, 25 Jun 2023 16:09:47 GMT
Connection: keep-alive
Keep-Alive: timeout=5
{&quot;success&quot;:false,&quot;error&quot;:{}}
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");

在这里,userproject 都未定义。请检查 models/index.js 文件,确保正确导出了 userproject

附言:
我建议您学习如何使用 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(&quot;../models&quot;);

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

huangapple
  • 本文由 发表于 2023年6月25日 23:27:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/76551139.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定