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?– Sergio
@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?
– Luiz Henrique
In relation to
fs.readFileSync
it would be better to do thisasync
, 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. Withexpress.js
for example it is easier, otherwise you have to do something like this: http://stackoverflow.com/a/29046869/2256325– Sergio
Luiz, test this idea: https://jsfiddle.net/cezr3wzp/2/ if it works together as a response
– Sergio
@M8n running by your code, still the same
– Luiz Henrique
At first
var filePath = '.' + req.url;
converts the url to the file name and the Node should search, without specifying more files. Oindex.html
is specified because it is the only one that can open only with the empty url. That isdefault
. Forehead.– Sergio
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.
– Sergio