0

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!

gib65
  • 1,709
  • 3
  • 24
  • 58
  • Are you wanting to send a JSON or `x-www-form-urlencoded` payload? This is mostly dependent on what body-parsing middleware you have configured in Express. In either case, you will need to format `payload` accordingly – Phil Feb 02 '23 at 02:54
  • I've closed this with two related duplicates. On the client-side, you'll need to format the payload as `application/x-www-form-urlencoded`. This is most easily done using `URLSearchParams` (first dupicate). On the server-side, you'll need to have the `app.use(express.urlencoded())` middleware (second duplicate) – Phil Feb 02 '23 at 02:58

0 Answers0