I am currently facing an issue with making a post XMLHttpRequest to my Express server. Despite attempting to send a string, it seems that I am missing something crucial in my implementation.
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)
})
The inclusion of console.log('Got it')
confirms the successful transmission of the request.
Despite trying to set a request header using
xhr.setRequestHeader('Content-Type', 'plain/text');
, the communication was not executed as intended.
Instead, utilizing
xhr.setRequestHeader('Content-Type', 'application/json');
along with sending xhr.send(JSON.stringify({message: message}))
resulted in a successful transmission. However, this method involves handling a JSON object.
My dilemma lies in how can I successfully send a string over an XMLHttpRequest post request?