Caleb
Caleb

Reputation: 1

Expressjs halts handling requests after 6 and then resumes after significant time period passes

I have a simple program with the following files

server.js:

const express = require('express')
const bodyParser = require('body-parser')
const cors = require('cors')
app = express()

app.use(bodyParser.json())
app.use(cors())

app.post("/app", (req, res) => {
    console.log(req.body)
})

app.listen(8080)

index.html:

<!DOCTYPE html>
<html>
    <head>
        <title>Test</title>
    </head>
    <body>
        <button onclick="request()">clicke me</button>
        <script src="script.js"></script>
    </body>
</html>

script.js:

function request() {
    console.log("agsdr ejl;kn")
    fetch('http://localhost:8080/app', {
    method: 'POST',
    headers: {
        'Content-Type': 'application/json',
    },
    body: JSON.stringify({test: "test"}),
    })
    .then(response => response.json())
    .then(data => {
        console.log('Success:', data);
    })
    .catch((error) => {
        console.error('Error:', error);
    });
}

After the button is pressed 6 times the server stops handling the requests and then minutes later it resumes handling the requests made earlier.

Any idea why this is happening and how I can fix it?

Upvotes: 0

Views: 63

Answers (2)

Grey
Grey

Reputation: 529

Suggestion

You need to return a response back to the client. See addition with comment

const express = require('express')
const bodyParser = require('body-parser')
const cors = require('cors')
app = express()

app.use(bodyParser.json())
app.use(cors())

app.post("/app", (req, res) => {
    console.log(req.body)
    res.status(200).json({ body: req.body }) // This simply returns the request body back to the client, just for demo purposes
})

app.listen(8080)

Upvotes: 0

James Craig
James Craig

Reputation: 6854

This is because the calls to the /app endpoint don't respond with anything. You need to modify your /app your to respond with someting, e.g.

app.post("/app", (req, res) => {
    console.log(req.body)
    res.end();
})

Upvotes: 1

Related Questions