【问题标题】:request body is not working - MYSQL and Node JS请求正文不起作用 - MYSQL 和 Node JS
【发布时间】: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),但您只解码 mimetype application/jsonapplication/x-www-form-urlencoded 的主体。根据哪一边是正确的,要么更改邮递员请求中的 mimetype,要么查看有关如何在 express stackoverflow.com/questions/37630419/… 中处理 multipart/form-data 的问题
  • 这回答了你的问题了吗? How to handle FormData from express 4

标签: node.js


【解决方案1】:

我有同样的问题。我有以下内容:req.params.id。然后我将其更改为 req.params['id'] 并开始工作。显然, req.params 是一个对象而不是单个值。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-11-04
    • 1970-01-01
    • 1970-01-01
    • 2018-03-15
    • 2017-06-23
    • 1970-01-01
    • 2021-09-12
    相关资源
    最近更新 更多