Ejercicio chat

En el chat que ya tenemos vamos a incluir algunas mejoras:

– Evitar que se puedan mandar mensajes más largos de 140 caracteres
– Filtrar palabras malsonantes
– Posibilidad de enviar emoticonos
– Posibilidad de tener cuatro salas diferentes de chat y elegir a cual te quieres conectar.

Server

http.createServer(function (req, res) {

    let url = "";
    let type = "text/html";
    if (req.url.endsWith(".css")) {
        url = "." + req.url;
        type = "text/css";
    } else if (req.url.endsWith(".js")) {
        url = "." + req.url;
        type = "text/javascript";
    } else {
        url = "pages" + (req.url=="/"?"/index":req.url) + ".html";
    }
    console.log(url);
    fs.readFile(url, function (err, data) {
        if (!err) {
            res.writeHead(200, { "Content-Type": type });
            res.end(data);
        }
        else {
            res.writeHead(404, { "Content-Type": "text/html" });
            res.end("<h1>Not found</h1>");
        }
    });
}).listen(port);

Empezando con express

npm i express

var express = require('express');
var app = express();

app.get('/', function (req, res) {
  res.send('Hello World!');
});

app.listen(3000, function () {
  console.log('Example app listening on port 3000!');
});

The general syntax for a route is shown below

app.METHOD(PATH, HANDLER)
Wherein,

1) app is an instance of the express module

2) METHOD is an HTTP request method (GET, POST, PUT or DELETE)

3) PATH is a path on the server.

4) HANDLER is the function executed when the route is matched

var express = require('express');
var app = express();
app.route('/Node').get(function(req,res)
{
    res.send("Tutorial on Node");
});
app.route('/Angular').get(function(req,res)
{
    res.send("Tutorial on Angular");
});
app.get('/',function(req,res){
    res.send('Welcome to Guru99 Tutorials');
}));
app.get("/items/:vegetable", (req, res) => {
let veg = req.params.vegetable;
res.send(`This is the page for ${veg}`);
});

middleware:

app.use((req, res, next) => {
console.log(`request made to: ${req.url}`);
next();
});
// An example middleware function
var a_middleware_function = function(req, res, next) {
  // ... perform some operations
  next(); // Call next() so Express will call the next middleware function in the chain.
}

// Function added with use() for all routes and verbs
app.use(a_middleware_function);

// Function added with use() for a specific route
app.use('/someroute', a_middleware_function);

// A middleware function added for a specific HTTP verb and route
app.get('/', a_middleware_function);

Para archivos estáticos:

app.use(express.static('public'));

Servidor muy sencillo

const routeResponseMap = {
  "/info": "<h1>Info Page</h1>",
  "/contact": "<h1>Contact Us</h1>",
  "/about": "<h1>Learn More About Us.</h1>",
  "/hello": "<h1>Say hello by emailing us here</h1>",
  "/error": "<h1>Sorry the page you are looking for is not here.</h1>"
};

const port = 3000,
  http = require("http"),

  app = http.createServer((req, res) => {
    res.writeHead(200, {
      "Content-Type": "text/html"
    });
    if (routeResponseMap[req.url]) {
      res.end(routeResponseMap[req.url]);
    } else {
      res.end("<h1>Welcome!</h1>");
    }
  });
app.listen(port);
console.log(`The server has started and is listening on port number:${port}`);