I want to collect the data from a simple HTML form and send it to the server. Unfortunately, I am making some mistakes and the server is not receiving the data. The error in the console
POST http://localhost:3000/ net::ERR_CONNECTION_REFUSED
Here is my code.
server.js
var express = require("express");
var app = express();
let PORT = process.env.PORT || 3000;
// Middleware
app.use(express.static("public"));
app.use(express.json());
app.get("/", function(req, res) {
res.sendFile(__dirname + "./public/index.html");
});
app.post("/", function(req, res) {
console.log('kkk', req.body);
});
var server = app.listen(PORT, function() {
console.log("Express server listening on port " + PORT);
});
I am using XMLHttpRequest() to collect the data and here is the code.
const contactForm = document.querySelector('#contactForm');
let fullName = document.getElementById('fullName');
let email = document.getElementById('emailAddress');
let phone = document.getElementById('phoneNumber');
let message = document.getElementById('message');
contactForm.addEventListener('submit', (e) => {
e.preventDefault();
let formData = {
name: fullName.value,
email: email.value,
phone: phone.value,
message: message.value
}
let xhttp = new XMLHttpRequest();
xhttp.open('POST', '/');
xhttp.setRequestHeader('content-type', 'application/json');
xhttp.onload = function() {
console.log(xhttp.responseText);
if(xhttp.responseText == 'success') {
console.log('Email sent successfully');
fullName.value = '';
emai.value = '';
phone.value = '';
message.value = '';
}else {
console.log('Something went wrong');
}
}
xhttp.send(JSON.stringify(formData));
});
If you want to check it live.
https://contact2021.herokuapp.com/
On Server, I can see the response
