I'm using classic Javascript ajax to send a request with a payload to my backend (node.js). On the backend, I get the request but I'm not finding the payload in the request. I need help with this (please).
Here's the ajax call:
function signIn() {
const username = document.getElementById('username');
const password = document.getElementById('password');
ajax('auth/signin', 'POST', {username: username.value, password: password.value});
}
function ajax(endpoint, method, payload) {
const xhttp = new XMLHttpRequest();
const url = 'http://localhost:3000/' + endpoint;
xhttp.onreadystatechange = function() {
console.log('readyState: ', this.readyState);
if (this.readyState === 4) {
if (this.status === 200) {
console.log('success!');
} else {
console.log('error: ', JSON.stringify(this));
}
}
};
xhttp.open(method, url, true);
xhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
if (payload) {
xhttp.send(payload);
} else {
xhttp.send();
}
}
On the backend, I print out the request like this:
router.post('/signin', (req, res, next) => {
console.log('signing in');
fs.appendFileSync('log.txt', new Date().toString() + ': in auth.js : router.post/signin\n' + util.inspect(req, {depth: 7}));
});
This writes the request 7 layers deep to log.txt. I open log.txt, I see the request in all its gory detail, but when I do a search for the username or password I entered, I find nothing.
So either the payload (username/password) is not getting to the backend with the request, or it's more than 7 layers deep. I'm assuming it's the former, not the latter.
Is there anything wrong with how I'm making my ajax call? Is this not how you send a payload along with a request? Is it something else I'm doing wrong? Thanks!