I am recently struggling a lot with my first website, which i deployed: https://bidimdepru.de/login.
Basically, my problem is, that my website is sending a OPTIONS request before a POST request. I read a bit about it and it seems like it is happening because i add CORS to my backend server.
My Frontend Code:
const handleLoginRequest = () => {
var requestData = {
username: username,
password: password
}
const requestOptions = {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(requestData)
};
fetch("https://emptychat-backend.onrender.com/login", requestOptions)
.then(response => {
if (response.ok) {
response.json()
.then(data => {
auth.signin(data);
navigate("/home")
});
} else {
response.text()
.then(data => {
setToastProps({header: "Oops. Etwas ist schiefgelaufen!", body: data})
setShowToast(true);
})
}
})};
Backend server code:
app.use(express.json())
app.use(cookieParser())
app.use(cors({
origin: 'https://bidimdepru.de',
credentials: true
}));
// Login
app.post(`/login`, async (req, res) => {
try {
// Eingaben extrahieren
const { username, password } = req.body;
// Eingaben validieren
if (!(username && password)) {
return res.status(400).send("Alle Eingaben werden benötigt!");
}
// Validieren, ob User existiert
const user = await User.findOne({ username });
if (user && (await bcrypt.compare(password, user.password))) {
// Token erstellen
const token = jwt.sign(
{ user },
"my_secret_key",
{
expiresIn: "2h",
}
);
res.cookie("token", token, {
httpOnly: true,
sameSite: none,
secure: true,
})
const parseUser = {
_id: user._id,
name: user.name,
email: user.email,
username: user.username,
isAdmin: false,
};
return res.status(200).json({auth: true, user: parseUser});
} else return res.status(400).send("Username/Passwort-Kombination stimmt nicht überein.");
} catch (err) {
console.log(err);
}
});
So basically i could solve my problem, by changing the requestOptions of my fetch() to
const requestOptions = {
method: 'POST',
headers: { 'Content-Type': 'text/plain' },
body: JSON.stringify(requestData)
};
When i change the Content-Type to “text/plain” i am only sending one POST Request, but then i cant access the username, password from my req.body. Could i solve this, without changing the content-type? How can i get username and password out of req.body, when i stay with text/plain