I am trying to make a post request using AJAX request, to be able to store it in the database. I have a button using the onclick event to call the usernameCheck() function, inside of my bundle.js file created with browserify. My DataController.js file includes the add function I am using to add the username to the database. When I click the button after typing in my username, there is a connection to the database but the value for the body is undefined
usernameCheck()
function usernameCheck() {
var user = document.getElementById('userbox').value;
//var Filter = require('bad-words');
//var filter = new Filter();
var username = JSON.stringify(user);
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
console.log("RESPONSE TEXT: " + this.responseText);
}
else {
console.log("FAILED\nReady State: " + this.readyState + "\nStatus: " + this.status);
}
};
xhttp.open("POST", "/add", true);
xhttp.send(username);
DataController.js
module.exports = {
add: function (req, res) {
var user = req.body.username;
console.log(user);
console.log(req.param());
Data.create({ username: user }).exec(function (err) {
if (err) {
res.send(500, { err: 'Database Error' });
}
else {
console.log("WORKS");
return res.ok();
}
})
}
};
This is how I have the route set up
'POST /add': 'DataController.add'
Bash and console
FAILED
Ready State: 1
Status: 0
FAILED
Ready State: 2
Status: 200
FAILED
Ready State: 3
Status: 200
RESPONSE TEXT: OK
XHR finished loading: POST "http://localhost:1337/add".
Database
[
{
"createdAt": 1592347252042,
"updatedAt": 1592347252042,
"id": "5ee94a7496f3a93aece14da3",
"username": ""
}
]
