I have a website and an express server running. In the website, the user can input their username and password. When they click the login button, the request is sent to the server with the username and password in the request body as a JavaScript object.
Here's the website code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Log In</title>
<link href="style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<h1>Log In</h1>
<div id="i">
<input type="text" name="u" id="u" placeholder="Username">
<input type="password" name="p" id="p" placeholder="Password">
<input type="submit" onclick="login()" value="Log In">
<div id="msg"></div>
</div>
<script src="script.js"></script>
</body>
</html>
JS:
let u = document.getElementById("u");
let p = document.getElementById("p");
let msg = document.getElementById("msg");
let xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
console.log("Server request is ready. Press login to send request.")
}
};
//login function triggered when user clicks login
function login() {
data = {
"username": u.value,
"password": p.value
}
xhttp.open("POST", "SERVER_URL", true);
xhttp.send(data)
}
But on the server-side, the request body shows empty:
// environment variables
const client = process.env['MAIN_CLIENT'];
// imports
const express = require('express');
const path = require('path');
const bodyParser = require('body-parser');
//init
const app = express();
app.use(bodyParser.urlencoded({ extended: true }));//app.use(bodyParser);
app.use(bodyParser.json());
app.get('/', (req, res) => {
res.sendFile(`${__dirname}/index.html`)
})
app.use((req, res, next) => {
res.setHeader("Access-Control-Allow-Origin", client);
next();
});
app.post(`/data`, (req, res) => {
console.log(req.body)
u = req.body.u;
p = req.body.p;
data = process.env;
console.log("----------------")
if (data[u] == p) {
console.log(`\n-/-/-/-/-/-/-/-/-/-/-/-/\nA user just logged in.\nUsername: ${u}\n-/-/-/-/-/-/-/-/-/-/-//-/ \n`)
res.send(true)
}
else{
console.log("no")
res.send(false)
}
});
app.listen(3000, () => {console.log('ready!')});
Whenever I try to log in, it shows the username as undefined. The request body shows as {}
Also, the variable CLIENT is the website URL.
Am I sending the request in the wrong way? Am I accessing the request body wrong?