1

I have created a websocket connection for the purpose of serving webrtc requests/answers (client):

export function webSocketConnect(room_code, action, username){
    let scheme = "ws"; 
    /* If the protocol is https you must use web socket secured */
    if(document.location.protocol === "https:"){
        scheme += "s";
    }
    getServerURL = createGetterForParam(hostname + ":" + server_port); 
    let websocketScheme = scheme + "://" + getServerURL.get(); 
    log("Server URL is: " + websocketScheme);

    try{
        web_socket_connection = new WebSocket(websocketScheme, "json"); 
    }catch(err){
        throw new Error("couldn't connect you to the server"); 
    }
    //assign event handlers 
   ...
}

This connects to a node js server(server):

try{
   http_s_server = https.createServer(
     https_options, 
     handleHttpsRequest
   );
  log("Created a https server");
}catch(err){...}
http_s_server.listen(port, function(){
  log("Https server is listening on port: " + port); 
}); 

web_socket_server = new WebSocketServer({
    httpServer: http_s_server,
    autoAcceptConnections: false, 
}); 
web_socket_server.on('request',async function(request) {
    log("request received");
    let connection = request.accept("json", request.origin); 
    assignConnectionHandlers(connection); 
    ... 
}

I want to upload a file to the server and I'm using a post request(getting the file from <input type="file"...>,client):

let new_filename = getUsername.get() + "_" + getClientID.get() + "_" + getRoomCode.get() + "_" + file.name;  
let formdata = new FormData(); 
formdata.append("file", file, new_filename); 
fetch(window.location.protocol + "//" + getServerURL.get() + "/Files", {
  method: "POST",
  body: formdata
})
.then(response => {
 // handle the response here
 log(JSON.stringify(response)); 
})
.then(data => {
  // handle the data here
})
.catch(err => {
  log(err);
});  

And in the server using the formidable framework:


function handleHttpsRequest(request, response){
    let processed_url = request.url.split("?")[0];
    let params =  request.url.split("?")[1];
    if (request.method === 'POST' && processed_url === '/Files') {
        handleSendFile(request, response); 
    }
}

function handleSendFile(request, response){
    var form = formidable.IncomingForm();
    form.on('fileBegin', function(name, file){
        file.path = localFilePath + file.name; 
    });

    form.on('file', function(name,file){
        log('Uploaded file: ' + file.name);
    });

    form.parse(request);

    response.writeHead(200, {'Content-Type': 'text/plain'}); 
    response.end(); 
}

The html where I'm getting the file:

<div class="chat-input-icon">
  <label for="file-input">
    <img id="file-input-image" src="../images/open-explorer.png" alt="File icon">
  </label>
</div>
<input type="file" id="file-input" name="file_input" style="display:none;">

The file is successfully saved into the desired directory in the server, but the websocket connection always crashes and I'm getting a:

Error: read ECONNRESET  

I have also tried using multiple versions for formidable and nothing seems to work.

I have also tried doing this based on a more standard form and then handling with onsubmit-> event.preventDefault():

<form action="https://localhost:62000/Files" id="upload-file-form" enctype="multipart/form-data" method="post">
  <div>Text field title: <input type="text" name="title" /></div>
  <div>File: <input type="file" name="multipleFiles"  /></div>
  <input type="submit" value="Upload" />
</form>   

Does anyone know a fix? (Any better implementation is accepted)

Fotis Bis
  • 21
  • 5
  • If you're using a `
    ` in the client to get the values to send, then perhaps your submit button is causing the web page to reload (thus killing the webSocket connection from that original page). We'd have to see more of the client side to know if that is indeed happening, but it is a common problem with Javascript posts hooked up to a form.
    – jfriend00 Dec 31 '22 at 05:10
  • Hi @jfriend00. I updated my question based on what you suggested. – Fotis Bis Dec 31 '22 at 10:45

1 Answers1

1

I solved it for everyone that shares the problem. I was having a CORS problem and I was setting the headers to accept CORS requests. After I was serving my content properly, meaning that I was requesting from the same domain I loaded the resources from, the problem was fixed.

More detailed:

  1. Load your content using the webserver for example: https://127.0.0.1:62000
  2. Proceed to request to the same address displayed in the address bar of the document
  3. Should work fine now

More detailed answer on CORS: Why does my JavaScript code receive a "No 'Access-Control-Allow-Origin' header is present on the requested resource" error, while Postman does not?

MDN documentation: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS

Fotis Bis
  • 21
  • 5