'Deploying server on heroku showing errors

I am trying to make simple chatApp, while using localhost it worked but, as I deployed on heroku, it shows error.

Here is my app.js(server)

const cors = require('cors');
const express = require('express');
const app = express();
const WebSocket = require('ws');
const port = process.env.PORT || 3000

app.use(
  cors({
    origin: true,
    credentials: true,
  })
);

const server = app.listen(port, () => {
  console.log(port, 'waiting unitil connects');
});

app.get('/', (req, res) => {
  res.send('Hello World!');
});

const wss = new WebSocket.Server({ server, path: '/ws' });

wss.on('connection', (ws, req) => {
  // connection
  console.log('새로운 클라이언트 접속');
  ws.on('message', (message) => {
    // receiving message
    const json = JSON.parse(message.toString());
    json.time = Date.now()
    message = JSON.stringify(json)
    console.log(message.toString());
    wss.clients.forEach((client) => {
      if (client.readyState === WebSocket.OPEN) {
        client.send(message.toString());
      }
    });

      // Runs when client disconnects
  wss.on('disconnect', () => {
  });
  });
  ws.on('error', (err) => {
    // error 
    console.error(err);
  });
  ws.on('close', () => {
    // close
    console.log('Client close');
    clearInterval(ws.interval);
  });
});

I typed heroku logs --tail and errors have been shown below

2022-04-11T03:31:28.889702+00:00 heroku[web.1]: State changed from crashed to starting
2022-04-11T03:31:31.177300+00:00 heroku[web.1]: Starting process with command `npm start`
2022-04-11T03:31:32.448811+00:00 app[web.1]: Error: No such file or directory
2022-04-11T03:31:32.653216+00:00 heroku[web.1]: Process exited with status 126
2022-04-11T03:33:20.806756+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=peaceful-ridge-59102.herokuapp.com request_id=9edd83f1-d40c-4319-8c17-0c1e1afc5999 fwd="59.9.54.226" dyno= connect= service= status=503 bytes= protocol=https

and this is my package.json script on server

  "scripts": {
    "start": "node app.js",
    "startNodemon": "nodemon --watch src/ src/app.js",
    "test": "echo \"Error: no test specified\" && exit 1"
  },

package.json and app.js are loacated in same folder which is root.

This is my client chat.vue

  created() {
    this.channel = this.$route.query.channel || '';
    // this.$store.state.user.stateWebSocket= new WebSocket('ws://localhost:3000/ws');
    this.$store.state.user.stateWebSocket = new WebSocket('ws://peaceful-ridge-59102.herokuapp.com/ws');
    this.websocket=this.$store.state.user.stateWebSocket;
    
    this.websocket.onmessage = ({ data }) => {
      const vo = JSON.parse(data);
      if (vo.channel === this.channel) {
        this.appendNewMessage(this.tempName, vo.message, vo.time);
      }
    };
    this.websocket.onopen = (event) => {
      console.log('open event..', event);
      
    };

    this.websocket.onerror = (event) => {
      console.log('error', event);
    };
     this.websocket.onclose = (event) => {
            console.log('close', event); 
    };
   
  },

On chat.vue there is click method that make websocket be closed. Below is perfectly working.

    onClickleaveRoom(event){
        event.preventDefault();
         this.$router.replace('/')
         if(this.$store.state.user.flag==true){
           this.websocket.close();
           this.$store.state.user.flag=false;
         }    
    }

However when I started chatApp and tried connect, I see the below error on web console

main.js:2 WebSocket connection to 'wss://peaceful-ridge-59102.herokuapp.com/ws' failed: 
main.js:2 WebSocket is already in CLOSING or CLOSED state.

I use router-link to go another tab and I put click method on it.

clickEventSocket(event){
     this.websocket=this.$store.state.user.stateWebSocket;
      if(this.websocket===WebSocket.OPEN && this.$store.state.user.flag===true){
        this.websocket.close()
        this.$store.state.user.flag=false;
      }
    }

I tried to close just clicking another tab, even I don't press leaveButton so the websocket can be closed and there is no left.

I tried to find the problems for 3 days... I can't find the answer plz help me if you know.

Update: And I tried this below server configuration too, changed package.json script app.js to server.js However still don't work.

const cors = require('cors');
const express = require('express');
const app = express();
const WebSocket = require('ws');
const PORT = process.env.PORT || 3000
const expressWs = require('express-ws')(app)
app
  .use(epxress.json())
  .listen(PORT, ()=>console.log(`Listening on ${PORT}`))

app.use(cors())
app.get('/', (req, res) => {
  res.send('Hello World!');
});

// const wss = new WebSocket.Server({ server, path: '/ws' });

app.ws('/', (ws, req) => {
  // connection
  console.log('새로운 클라이언트 접속');
  ws.on('message', (message) => {
    // receiving message
    const json = JSON.parse(message.toString());
    json.time = Date.now()
    message = JSON.stringify(json)
    console.log(message.toString());
    expressWs.getWss().clients.forEach((client) => {
      if (client.readyState === WebSocket.OPEN) {
        client.send(message.toString());
      }
    });

      // Runs when client disconnects
  ws.on('disconnect', () => {
  });
  });
  ws.on('error', (err) => {
    // error 
    console.error(err);
  });
  ws.on('close', () => {
    // close
    console.log('Client close');
    clearInterval(ws.interval);
  });
});

plz advise me...



Sources

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

Source: Stack Overflow

Solution Source