Post request to server is giving me error in express net::ERR_CONNECTION_REFUSED

Viewed 940

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

enter image description here

1 Answers

Testing your live site, I see that it hangs when posting to https://contact2021.herokuapp.com/. Presuming that this route is defined by the following:

app.post("/", function(req, res) {
    console.log('kkk', req.body);
});

an issue is that you will need to initiate some kind of response, using one of the methods on Response (eg res.end(), res.send()).

This is likely not the same issue as the connection to localhost:3000, but if you are trying to access the site from any machine other that the one hosting it in development, then that connection wouldn't work, as it would be trying to connect to itself at that port.

Related