Search code examples
javascriptnode.jsexpresspostfetch

Why does fetch in the browser send an empty body to my API unlike a API Client like Insomnia


I am currently trying to create a login system with a Mongo Database, but it won't work when I try to fetch POST the login credentials to my express.js API via the Chrome Browser. Unlike in any browser itt works when I use the Insomnia Client. I personally think the problem is either in the header or middleware part of the code. I am grateful for every indication where my problem might be.


Code:

Login function:

async function login() {
  const data = getUserDataEncrypted(); //gets username and password

  await fetch(url + "/checkUser/login", {
    method: "POST",
    mode: 'cors',
    headers: {
      "Content-Type": "application/json"
  },
    body: JSON.stringify(data)
  }).then(res => {
    console.log(res.json());
  });
}

Used Middleware:

require('dotenv').config();

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

app.use(require("cors")());
app.use(express.json());
app.use(require("morgan")("combined"));

Server Side:

router.post('/login', async (req, res) => {
    try {
        const user = await User.find({ username: req.body.username });

        if (user[0].password === req.body.password) {
            res.send({
                message: "Successfull Login",
                login: true
            });
            return;
        } else {
            res.send({
                message: "Password incorrect",
                login: false
            });
            return;
        }
    } catch (error) {
        res.send({
            message: error.message,
            req: req.body
        });
    }
});

User Data:

async function getUserDataEncrypted() {
  var username = document.getElementById("username").value;
  var password = document.getElementById("password").value;

  password = await SHA256Encyption(password);

  const data = {
    username: username,
    password: password
  }

  return data;
}

Images:

Insomnia

API Response


Solution

  • In the login function, try to console.log the data from getUserDataEncrypted().

    If its null or undefined try to use await.

    await getUserDataEncrypted();