Express - req.body does not find the data sent by the customer

Asked

Viewed 216 times

1

I have a small form with login and password whose data I need to be sent to a route X via POST. For this, I used AJAX and to make sure that the data was being sent, I used the Success function to show a feedback log. The problem is, on the route responsible for receiving this data, I can’t access it. I’m using Express and as far as I know, to access the data you must use req.body.nameDado, but when doing this the value returned is Undefined. How can I fix this?

Customer Javascript for sending data

$("#btn-signin").click((e) => {
  (async () => {
    try {
      const login = $('#loginform').val()
      const password = $('#passwordForm').val()

      await $.ajax({
        url: "http://localhost:8081/Auth/check-signin",
        method: "POST",
        data: {
          login: login,
          password: password
        },
        success: console.log('Dados enviados!')
      })

      const res = await apiResponse()

      if (res.errorMessage) {
        alert(res.errorMessage)
      }

    } catch (error) {
      console.log(`Error: ${error}`)
    }
  })()
})
  • In case my answer does not resolve, I suggest you edit the post including the code of your back-end. That way other people can more easily identify where the error is.

2 answers

1

What is your version of Node? In newer versions, it is not necessary to use Bodyparser. The configuration I make in my applications is as follows:

const express = require("express")
const cors = require("cors")

const app = express()

app.use(cors())
app.use(express.json())
app.use(express.urlencoded({ extended: true })

0

How your express is configured?

You can use the bodyparser to be able to receive the data. You can apply this way here:

const express = require('express');
const app = express();

app.use(express.bodyParser());

With this config you should be able to get the data sent.

  • I’m already wearing the body parser, that’s the thing. const Bodyparser = require('body-parser') App.use(Bodyparser.urlencoded({Extended: true})) App.use(Bodyparser.json())

Browser other questions tagged

You are not signed in. Login or sign up in order to post.