Node.js sending GET command

Asked

Viewed 365 times

0

Hello! I am having trouble using the GET /test command in this case, in which no information returns.

Node.js code

var http = require("http").createServer(servidor);
var express = require('express');
var io = require("socket.io").listen(http);
var app = express();
var fs = require("fs");
var recebido;

var contentTypes = {
    js: 'text/javascript',
    css: 'text/css',
    json: 'application/json',
    png: 'image/png',
    jpg: 'image/png',
    wav: 'audio/wav'
};

function servidor(req, res) {
    var contentType = 'text/html';
    var filePath = '.' + req.url;
    if (filePath == './' || filePath == './index.html') filePath = './index.html';
    else contentType = contentTypes[req.url.split('.').pop()];

    fs.readFile(filePath, function(error, content) {
        if (error) {
            if (error.code == 'ENOENT') {
                fs.readFile('./404.html', function(error, content) {
                    res.writeHead(200, {
                        'Content-Type': 'text/html'
                    });
                    res.end(content, 'utf-8');
                });
            } else {
                res.writeHead(500);
                res.end('Ooops... houve um erro: ' + error.code + ' ..\n');
                res.end();
            }
        } else {
            res.writeHead(200, {
                'Content-Type': contentType
            });
            res.end(content, 'utf-8');
        }
    });
}

io.on("connection", function(socket) {
    socket.on('mensagem', function(msg) {
        console.log('Recebido: ' + msg);
        recebido = msg;
    });
});

app.get('/teste', function(req, res) {
    res.charset = 'UTF-8'
    res.send(recebido);
});


http.listen(5000, "192.168.0.108", function() {
    var host = http.address().address;
    var port = http.address().port;
    console.log('Exemplo na URL http://%s:%s', host, port);
});

When using the GET /test command or http://192.168. 0.108/test, the page loads blank

  • res.end(fs.readFileSync is a very bad idea. Of course for those who start with Node.js it is not easy to know this. You want to use only "native" Node or you can join a Node framework to a server with more functionality?

  • @The idea is to use Node only for communication with Arduino (ESP8266 via GET command) and HTML with Socket i.o. What is your idea?

  • 2

    In relation to fs.readFileSync it would be better to do this async, cache the file and serve as memory. To serve files you must send the header with the file type and you must read/interpret each requested url and serve the file. With express.js for example it is easier, otherwise you have to do something like this: http://stackoverflow.com/a/29046869/2256325

  • 1

    Luiz, test this idea: https://jsfiddle.net/cezr3wzp/2/ if it works together as a response

  • @M8n running by your code, still the same

  • At first var filePath = '.' + req.url; converts the url to the file name and the Node should search, without specifying more files. O index.html is specified because it is the only one that can open only with the empty url. That is default. Forehead.

  • Socket io is for communication/chat between clients. Is that what you need? If you only have simple html files you don’t need it.

Show 2 more comments

1 answer

1

var http = require("http").createServer(servidor);
var io = require("socket.io").listen(http);
var fs = require("fs");

function servidor(req, res){
    if (req.url.indexOf('/') != -1) {
        res.writeHead(200);
        res.end(fs.readFileSync("index.html"));
    }

    if (req.url.indexOf('css/bootstrap.min.css') != -1) {
        res.writeHead(200, {"Content-Type": 'text/css'});
        res.end(fs.readFileSync("css/bootstrap.min.css"));
    }

    if (req.url.indexOf('css/sb-admin.css') != -1) {
        res.writeHead(200, {"Content-Type": 'text/css'});
        res.end(fs.readFileSync("css/sb-admin.css"));
    }

    if (req.url.indexOf('font-awesome/css/font-awesome.min.css') != -1) {
        res.writeHead(200, {"Content-Type": 'text/css'});
        res.end(fs.readFileSync("font-awesome/css/font-awesome.min.css"));
    }
}

io.on("connection", function(socket){
    socket.on('mensagem', function(msg) {
        console.log('Recebido: ' + msg);
    });
});

http.listen(5000, "127.0.0.1", function () {
    var host = http.address().address;
    var port = http.address().port;

    console.log('Exemplo na URL http://%s:%s', host, port);
});
  • 2

    Why are you using socket.io? If it’s just to get the Connection event, the http object above also receives this event.

  • @Joséx. I did according to the module of the Socket site i.o. What would be your idea?

  • In this example you do not need socket.io...instead of io.on("connection) could be http.on("connection"). The module socket.io is not adding any functionality.

  • @Joséx. socket.io serves to create a Websocket connection.

  • 1

    But this example does not use websocket, so it does not need socket.io.

  • @Joséx. My HTML is sending information to Socket... There is a way I can change the Node code to work Socket i.o and also GET /test?

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.