'Express or Axios Error: socket hang up code: ECONNRESET

This is the first time i post a question here, sorry if some data is missing.

I'm trying to do some web scraping to get some info of a table. The page only responds with an index.php and when i use the search form, it makes a POST to index.php?go=le with some formData. To avoid the CORS problem, im making the post with my own API running in localhost. I'm pointing my frontend to my API and i get the response from localhost. No problem there.

My problem appears when i try to make a second request to my API. The first GET works fine but after that response it keeps failing.
When i restart the server, it works again but only one time.

Here is my API code. I use nodemon server.js to start my server.

server.js

const express = require("express");
const axios = require("axios");
const scrape = require("scrape-it");
const FormData = require("form-data")
const cors = require("cors")

const app = express();
const PORT = process.env.PORT || 5000;

app.use(cors())

const config = {
    headers: {
        'Content-type': 'multipart/form-data'
    },
    
}

app.get("/get-projects", async (req,res) => {
    const testJSON = await axios.post(baseURL +"/index.php?go=le",formData,config)
        .then(res => {
                console.log("Post successfull...");
                return res
                }
            )
        .catch(err => {
            console.log("Server error");
            return err
            }
            );
    if(testJSON && testJSON.data){
        res.send({status: 200, data: testJSON.data});
    }else{
        res.status(508).send({status: 508, msg: "Unhandled Server Error", failedResponse: testJSON || "empty"})
    }
})


app.listen(PORT,()=>console.log(`App running in port: ${PORT}`))

And in my front-end i only have a button with an event that makes a get to my API (http://localhost:5000)

This is my fetch.js that is included by a script tag. Nothing fancy there.

fetch.js

const btn = document.getElementById("btn-fetch-proyects")
const axios = window.axios

const fetchProjects = async () => {
    console.log("Fetching...")

    axios.get("http://localhost:5000/get-projects")
    .then(res=>
        console.log("The server responded with the following data: ",res.data)

    )
    .catch(err => console.log("Failed with error: ",err)
    )
    
    return null
}

btn.addEventListener("click",fetchProjects);

In the console where im running the server, i get Server error with this err object:

{
    "message": "socket hang up",
    "name": "Error",
    "stack": "Error: socket hang up\n    at connResetException (internal/errors.js:607:14)\n    at Socket.socketOnEnd (_http_client.js:493:23)\n    at Socket.emit (events.js:327:22)\n    at endReadableNT (internal/streams/readable.js:1327:12)\n    at processTicksAndRejections (internal/process/task_queues.js:80:21)",
    "config": {
        "url": "http://186.153.176.242:8095/index.php?go=le",
        "method": "post",
        "data": {
            "_overheadLength": 1216,
            "_valueLength": 3,
            "_valuesToMeasure": [],
            "writable": false,
            "readable": true,
            "dataSize": 0,
            "maxDataSize": 2097152,
            "pauseStreams": true,
            "_released": true,
            "_streams": [],
            "_currentStream": null,
            "_insideLoop": false,
            "_pendingNext": false,
            "_boundary": "--------------------------935763531826714388665103",
            "_events": {
                "error": [
                    null,
                    null
                ]
            },
            "_eventsCount": 1
        },
        "headers": {
            "Accept": "application/json, text/plain, */*",
            "Content-Type": "multipart/form-data",
            "User-Agent": "axios/0.21.1"
        },
        "transformRequest": [
            null
        ],
        "transformResponse": [
            null
        ],
        "timeout": 0,
        "xsrfCookieName": "XSRF-TOKEN",
        "xsrfHeaderName": "X-XSRF-TOKEN",
        "maxContentLength": -1,
        "maxBodyLength": -1
    },
    "code": "ECONNRESET"
}

I hope someone has a clue about what's happening. I tried all day and i couldn't solve it.
I tried posting to other sites, and it works fine. I thing the problem is with the form POST.

Thanks for reading!!!



Solution 1:[1]

At a first glance I see an error in your front-end code. You are using async on the function but then you do not await but you use .then, try not mixing up styles, either you use async/await or .then .catch.

Check if that helps! :)

Solution 2:[2]

Obviously the socket is hanging! Use node unirest and it closes the data stream.

var unirest = require('unirest');
var req = unirest('POST', 'localhost:3200/store/artifact/metamodel')
  .attach('file', '/home/arsene/DB.ecore')
  .field('description', 'We are trying to save the metamodel')
  .field('project', '6256d72a81c4b80ccfc1768b')
  .end(function (res) { 
    if (res.error) throw new Error(res.error); 
    console.log(res.raw_body);
  });

Hope this helps!

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Mattia Rasulo
Solution 2 Arsene Online