-1

i have created a socket.io web app, when i click on the button to send a message, the message appears for a second, but when the page refreshes automatically for no reason, the message dissapears. How can i prevent the page from refreshing and how can i make socket.io save my messages.

Here is the server code:

var express = require("express");
var io = require("socket.io")(4000);
var fetch = require("node-fetch");
var express = require("express");
var bodyParser = require("body-parser");

var app = express();

io.on("connection", (socket) => {
  socket.on("message", (msg) => {
    io.emit("message", msg);
  });
});

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

var stats = [];

app.post("/api", (request, response) => {
  var key = "E9BEFD12B99EF8838E61F7A74D9C6A4B";
  fetch(
    `http://api.steampowered.com/ISteamUserStats/GetUserStatsForGame/v0002/?appid=730&key=${key}&steamid=${request.body.user}`
  )
    .then((res) => res.json())
    .then((json) => response.send(json) | stats.push(json));
});

app.listen(3000, () => {
  console.log("server running");
});

And here is the client code:

var socket = io("ws://localhost:4000/");

var send = () => {
  socket.emit("message", document.getElementById("message").value);
  document.getElementById("message").value = " ";
  return false;
};

socket.on("message", (msg) => {
  document.getElementById("messages").innerHTML = "<p>" + msg + "</p>";
});

The send function executes whenever i press a button.

E_net4
  • 27,810
  • 13
  • 101
  • 139
DCAdarko
  • 1
  • 2
  • 1
    I guess the button you are pressing is in a form, which triggers the default action, thus loading the same page again – Seblor Sep 23 '20 at 15:26
  • 1
    What @Seblor said - you should post the HTML for your page. That's probably where the problem lies. – Kryten Sep 23 '20 at 15:27
  • 1
    Does this answer your question? [prevent refresh of page when button inside form clicked](https://stackoverflow.com/questions/7803814/prevent-refresh-of-page-when-button-inside-form-clicked) (or [How to stop page reload on button click jquery](https://stackoverflow.com/questions/33465557/how-to-stop-page-reload-on-button-click-jquery/)) – Seblor Sep 23 '20 at 15:27
  • 1
    @Seblor i removed the form tags from the html and now it works, thanks mate – DCAdarko Sep 23 '20 at 15:44
  • @DCAdarko you should write your solution as an answer in case someone finds your question later through Google for example – Seblor Sep 23 '20 at 15:53
  • @Seblor oh, you're right, now i added the answer to my question. – DCAdarko Sep 23 '20 at 18:06

1 Answers1

0

To fix this, i just removed the form tags from the html file, the problem was every time when the form was submitted the page refreshed by default.

DCAdarko
  • 1
  • 2