Page reloads after form request

Posted 1 year ago by Rainieren

Hello, I'm currently following Jeffery's tutorial about socket io. I'm at the first part. But I have a small problem. I have the same code as him until the part where he adds the function that prints out the message in the console. But my page just refreshed when I press the button, and I can't figure out why? The only thing I did was change a couple of the variable names. I came to an understanding that this has something to do with e.preventDefault(); But I could be wrong, but I don't know. If it does, It somehow does not work for me. Any suggestions on how to solve this issue? I'll leave my code below, Just for sure

Index.js

var app = require('express')(); //Express is een framework die ik gesinstalleerd heb via npm install express. Wat het doet weet ik niet maar ik haal het binnen via hier
var server = require('http').Server(app); //Dit maak een nieuwe server aan
var io = require('socket.io')(server); //Haalt socket.io op

server.listen(8000, function() {

}); //Hij luistert af naar htdocs met poort nummer 8000

app.get('/', function(request, response) { //Hier pakt hij de hoofdpagina en alles wat je erin zet wordt uitgevoerd
    response.sendFile(__dirname + '/index.html');
});

io.on('connection', function(socket) {
    socket.on('chat.bericht', function(bericht) {
        console.log('Nieuw Bericht: ' + bericht);
    });
    console.log('Er is iemand verbonden met de server!')
});

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Real time Project</title>
</head>
<body id="chat">
    <form v-on="submit: send">
        <input v-model="bericht">
        <button type="submit">Verzend naar de server</button>
    </form>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.0.4/socket.io.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.2/vue.min.js"></script>
    <script>
        var socket = io();

        new Vue({
            el: '#chat',

            data: {
                bericht: ''
            },

            methods: {
                send: function(e) {
                    socket.emit('chat.bericht', this.bericht);

                    e.preventDefault();
                }
            }
        })
    </script>
</body>
</html>

Please sign in or create an account to participate in this conversation.

Laracasts Mascot

Hi, Have We Met Yet?

Did you know that, in addition to the forum, Laracasts includes well over 1000 lessons on modern web development? All for the price of one lunch out per month.

Sign Me Up

Channels

Reply to

Use Markdown with GitHub-flavored code blocks.