0

I have a HTML form as follows:

<form id="loginForm" name="loginForm">
   <div class="form-group">
   <input type="username" class="form-control" id="username" name="username" placeholder="Your username..." >
   </div>
   <div class="form-group">
   <input type="password" class="form-control" id="password" name="password" placeholder="Your password...">
   </div>
   <button class="btn btn-primary btn-block btn-round" id="loginButton" type="submit">Login</button>
</form>

and a Javascript file containing the following code to make an AJAX request:

//credits to @lndgalante
if (typeof window !== 'undefined') {
  window.addEventListener('load', () => {
        const form = document.getElementById('loginForm');

        form.addEventListener('submit', async (event) => {
        event.preventDefault();

        const elements = event.target;
        const username = elements.username.value;
        const password = elements.password.value;
        const dataToSend = { username, password };

        try {

         console.log(JSON.stringify(dataToSend)); //To check variables are being passed correctly

         return await fetch('/login', {
            method: 'POST',
            body: JSON.stringify(dataToSend),
            headers: { 'Content-Type': 'application/json' }
          });
        } catch (error) {
          console.log(error);
        }
      });
    });
  };

and a node.js file with the corresponding POST route:

app.post('/login', async (req, res) => {
    try {
      const username = req.body.username;
      const password = req.body.password;
      console.log(username, password, req.body); //To check variables are being passed correctly
    ...
    }
});

But the problem is, console.log(JSON.stringify(dataToSend)); returns {"username":"username1","password":"password1"} //or whatever the user input is as expected, whereas console.log(username, password, req.body) returns undefined undefined {}.

Does anyone know what I'm doing wrong?

Edit: I am using const app = express(); and I have app.use(bodyParser.urlencoded({ extended: true })); in my node.js file.

bgmn
  • 498
  • 2
  • 7
  • 25

3 Answers3

1

Assuming you're using Express.js (you should probably tag the question) you need to make sure you use the express.json() (or bodyParser.json()) middleware for JSON body parsing.

const app = express();
app.use(express.json());
app.post('/login', ...);

Your client-side code is correct.

101arrowz
  • 1,825
  • 7
  • 15
  • Oh yes of course, how could I forget! Should I close this question since it may not be much help to others? – bgmn Apr 20 '20 at 20:47
1

I have app.use(bodyParser.urlencoded({ extended: true })); in my node.js file.

You're POSTing JSON, not URL Encoded data.

You need a JSON parser.

app.use(bodyParser.json());

… or to post URL Encoded data:

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
1

You must use a body parser, otherwise your NodeJS application will not know how to interpret your string received in the request body.

npm install --save body-parser

and

var bodyParser = require('body-parser')
app.use( bodyParser.json() );       // to support JSON-encoded bodies
app.use(bodyParser.urlencoded({     // to support URL-encoded bodies
  extended: true
})); 

or

app.use(express.json());
app.use(express.urlencoded());
app.use(express.multipart());

So your code will run propperly.

More details here: How to retrieve POST query parameters?

Caio Santos
  • 1,665
  • 15
  • 10