bratibrat bratibrat - 4 months ago 18
Javascript Question

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'});

var io = require('').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>
<script src=""></script>
<script src="/"></script>
var socketio = io.connect("");
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) {
});, textStatus) {
alert( "Request failed: " + textStatus );

function sendMessage() {
var msg = document.getElementById("message_input").value;
socketio.emit("message_to_server", { message : msg});

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

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



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");
    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);

    res.sendFile(__dirname + "/client/index.html");

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


And if you realy realy 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"});