【发布时间】:2022-08-06 00:11:06
【问题描述】:
我正在尝试使用 NodeJS、Express 和 Mysql 创建此 API,但是在 Postman 上进行测试时,虽然代码正在更新数据库中的值,但它不会读取我在请求正文中插入的信息.例如,我可以访问参数信息 (codAluno),但不能访问请求正文 (Empresa_Atual)。
我有两个 API 文件:routes.js 和 index.js
const express = require(\'express\')
const bodyParser = require(\'body-parser\')
const app = express()
const db = require(\'./routes\')
const port = 3000
app.use(
bodyParser.urlencoded({
extended: true,
})
)
app.use(bodyParser.json())
app.get(\'/\', (request, response) => {
response.json({ info: \'API\' })
})
app.get(\'/alunos\', db.getAlunos)
app.get(\'/alunos/:id\', db.getAlunoByCod)
app.post(\'/alunos/:id\',db.updateAluno)
app.listen(port, () => {
console.log(`App running on port ${port}.`)
})
和 routes.js
const mysql = require(\'mysql\');
// Set database connection credentials
const config = {
host: \'localhost\',
user: \'user\',
password: \'\',
database: \'student\',
};
// Create a MySQL pool
const pool = mysql.createPool(config);
const updateAluno = (request, response) => {
const codAluno = parseInt(request.params.id)
var Empresa_Atual = request.body.Empresa_Atual
pool.query(\'UPDATE aluno SET `Empresa_Atual`= ? WHERE `codAluno` = ?\', [Empresa_Atual, codAluno], (error, result) => {
if (error) throw error;
response.send(\'User updated successfully.\');
});
}
这是我通过邮递员发送的请求
例如,变量Empresa_Atual 始终为空,即使我将它分配给请求正文。
任何人都可以帮忙吗? 谢谢!
-
添加一些调试信息,以找出您的信息在哪里。 (并验证它是否在您认为的位置)
-
将您尝试发送的请求添加到问题...
-
你甚至在路线中导出任何东西吗?
-
您发送的请求类型为 \"formdata\"(即具有 mimetype
multipart/form-data),但您只解码 mimetypeapplication/json和application/x-www-form-urlencoded的主体。根据哪一边是正确的,要么更改邮递员请求中的 mimetype,要么查看有关如何在 express stackoverflow.com/questions/37630419/… 中处理multipart/form-data的问题 -
这回答了你的问题了吗? How to handle FormData from express 4
标签: node.js