maison.m
maison.m

Reputation: 863

POST to Node.js Server causing long load that results in an ERR_EMPTY_RESPONSE

I have a simple form that posts the users input to the server. After submitting the form, the page loads for a long time resulting in ERR_EMPTY_RESPONSE. However I am able to console.log the input from the form just fine to verify that the form is indeed posting to the server.

Here is what I'm working with:

<form method="post" action="/">
    <input type="text" name="userZipcode" placeholder="Enter your zip code">
    <button type="submit">ENTER</button>
</form>

and

app.use(bodyParser.urlencoded({
    extended: false
}));

app.use(bodyParser.json());

app.get('/', (req, res, next) => {
    fetch(url)
    .then(res => res.json())
    .then(data => res.render('pages/index'))
    .catch(err => {
        console.log(err);
        res.sendStatus(500);
    });
});

app.post('/', function(req, res) {
    let zipcode = req.body.userZipcode;
    console.log('Your location is: ' + zipcode);
});

Note: The fetch request will eventually pass data from the API response into my EJS page, but for now it does nothing but render the index page.

The form above works, I get a console.log with a zipcode from the input field in my terminal as expected. However, afterwards the page just loads until it ends in the error mentioned above. I know I am missing something important, but I do not know what that is!

Upvotes: 1

Views: 265

Answers (1)

Wesgur
Wesgur

Reputation: 3237

In your POST route you have to put a response. Your code is not responding back to the request. This leads to ERR_EMPTY_RESPONSE.

app.post('/', function(req, res) {
    let zipcode = req.body.userZipcode;
    console.log('Your location is: ' + zipcode);
    res.end("your response");
});

Upvotes: 5

Related Questions