Search code examples
javascriptexpressxmlhttprequest

Send plain text over XMLHttpRequest to Express server


I'm making an XMLHttpRequest post request to my Express server. I'm trying to send a string, but I'm doing something wrong.

Client:

const sendMessage = () => {
  const message = "This is a test."
  var xhr = new XMLHttpRequest();
  xhr.open('POST', '/messages/api/new-message/', true)
  xhr.onload = function() {
    if (this.status == 200) {
      const response = JSON.parse(this.responseText);
    }
  }
  xhr.send(message)
}

Server:

router.post('/api/new-message', (req, res, next) => {
  console.log('Got it')
  console.log('req.body\n', req.body)
})

console.log('Got it') ensures that the request is going through successfully.

I also tried setting a request header: xhr.setRequestHeader('Content-Type', 'plain/text');, but it still didn't go through.

What does work is xhr.setRequestHeader('Content-Type', 'application/json'); and xhr.send(JSON.stringify({message: message})), but that's a JSON object.

How do I send a string over an XMLHttpRequest post request?


Solution

  • I noticed that you tried plain/text, but that is incorrect, the correct header is text/plain.

    from MDN

    • using the POST method and setting the enctype attribute to application/x-www-form-urlencoded (default);
    • using the POST method and setting the enctype attribute to text/plain;
    • using the POST method and setting the enctype attribute to multipart/form-data;
    • using the GET method (in this case the enctype attribute will be ignored).

    https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest