bratibrat
bratibrat

Reputation: 65

Routing with node

I am trying to understand how to build a Node.js project.

I have followed a tutorial I found to make a chat app.

The routing between the server side and the client side is not working. If you could explain to me why, or, maybe give me a good reference to understand how its all should work together ?

This is the server:

    var http = require('http');
    const fs = require('fs');
    var Router = require('router')

    var router = Router();
    router.get('/test', function (req, res) {
        res.setHeader('Content-Type', 'text/plain; charset=utf-8');
        res.end('Hello World!');
    })

    var app = http.createServer(function (request, response) {
        fs.readFile("public/client.html", 'utf-8', function (error, data) {
            response.writeHead(200, {'Content-Type': 'text/html'});
            response.write(data);
            response.end();
        });
    }).listen(1337);


    var io = require('socket.io').listen(app);

    io.sockets.on('connection', function(socket) {
        socket.on('message_to_server', function(data) {
            io.sockets.emit("message_to_client",{ message: data["message"] });
        });
    }); 

And this is the HTML with the client script:

<!DOCTYPE html>
<html>
    <head>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
        <script src="/socket.io/socket.io.js"></script>
        <script> 
            var socketio = io.connect("127.0.0.1:1337");
            socketio.on("message_to_client", function(data) {
                document.getElementById("chatlog").innerHTML = (document.getElementById("chatlog").innerHTML + "<hr/>" + data['message']);
            });

            var request = $.ajax({
                           url: "/test",
                           type: "GET"  
                        });
            request.done(function(msg) {
                console.log(1111);
            });

            request.fail(function(jqXHR, textStatus) {
                alert( "Request failed: " + textStatus );
            });

            function sendMessage() {                
                var msg = document.getElementById("message_input").value;
                socketio.emit("message_to_server", { message : msg});
                window.scrollTo(0,document.body.scrollHeight);
            }
        </script>

    </head>
    <body>
        <div id="wholeChat">                
            <div id="chatlog"></div>                
            <div>
                <input type="text" id="message_input"/>
                <button onclick="sendMessage()">send</button>
            </div>
        </div>        
   </body>
</html>

Maybe using express or hapi will make things more simple, but then I can't understand how do I load the view like I'm doing here with the fs module.

Thanks!

Upvotes: 1

Views: 175

Answers (1)

Mario Rozic
Mario Rozic

Reputation: 254

I dont know why are you trying send index.hmml like that, there is much easier way to do that, like ..

var connect = require("connect");
var serveStatic = require("serve-static");
connect().use(serveStatic(__dirname)).listen(2000,function(){
    console.log("Server running on 2000...");
});

And just type localhost:2000/yourIndexFile.html

Or you can use express (which is awesome module you should learn it)..

var express = require("express");
var app = express();
var serv = require("http").Server(app);

app.get("/",function(req,res){
    res.sendFile(__dirname + "/client/index.html");
});

app.use("/client",express.static(__dirname + "/client"));

serv.listen(2000);

And if you really really want to use 'fs' module try adding this to your code in response header.

onRequest = function(req,res){       
    res.writeHead(200,{"Content-Type": "text/html"});
    fs.createReadStream("./index.html").pipe(res);    
}

http.createServer(onRequest).listen(2000);

Upvotes: 2

Related Questions