I am currently having an issue with my POST request.
I have a simple function that is responsible of sending data to my server using AJAX.
handleSubmit(event) {
var http = new XMLHttpRequest(); // object allwos us to make http requests
//Lets make a request
http.open("POST", "http://localhost:3000/register", true);//set up the request for us: type of request we want, where we want the data from, do we want it to be sync or async?
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
//each time the ready state changes on the http object, it will fire this function.
http.onreadystatechange = function(){
console.log(http); // lets see the ready state changing...
//once the ready state hits 4(request is completed) && status is 200 (which is okay), lets do something with data.
if(http.readyState == 4 && http.status == 200){
}else{
console.log('Error: ' + http.status); // An error occurred during the request.
}
}
let user = {
email: "[email protected]"
};
http.send(JSON.stringify(user));
}
My server side code is pretty simple and contains a POST end point.
const express = require('express')
const app = express()
const port = 3000
//Body Parser Middleware
app.use(express.json());
app.use(express.urlencoded({extended: true}))
app.post('/register', (req, res) => {
console.log(req);
})
app.listen(port, () => console.log(`Example app listening on port ${port}!`))
Now, once handleSubmit fires, the req body of my object becomes the following:
{ '{"email":"[email protected]"}': '' }
I am very confused and I'm not quite sure how to proceed.
Thank you!
Everything seems to be good, You have to declare the Header as json,
http.setRequestHeader("Content-type", "application/json");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With