Tutorial del Internet de las Cosas y Bluetooth con el ESP32
Juan Antonio Villalpando
Volver al índice del tutorial
____________________________
117.- ESP32 y Node.js. Servidor Web. WiFi. App Inventor.
- Vamos a instalar un Servidor Web en nuestro ordenador mediante Node.js y enviar/recibir información desde ESP32 a la aplicación y viceversa.
- Además veremos gráficos dinámicos en una página web y en la aplicación.
- La segunda parte de este tutorial se encuentra en: 117_Wemos_NodeJs_MySQL.htm, trata de la gestión de la base de datos MySQL.
____________________________________________
1.- Instalar Node.js en el ordenador.
- Podemos bajar la última version de: https://nodejs.org/es/download/
(It is open-source, cross-platform, JavaScript,
web server, dynamic web page,
real-time Web applications)
- En mi caso no me lo instaló ya que intenté instalarlo en Windows 7 y la última versión necesita una versión de Windows 8 o mayor.
- Así que bajé una versión anterior, además la bajé en portable:
https://nodejs.org/dist/latest-v8.x/ concretamente bajé la: node-v8.17.0-win-x64.zip
- Descomprimo el archivo y en esta carpeta encuentro el node.exe
- Ocupa unos 60 MB.
D:\Downloads\node-v8.17.0-win-x64\node-v8.17.0-win-x64
- Voy al símbolo de Sistema de Windows, para consultar la versión escribo node -v
- Vamos a realizar un "Hola mundo" directamente, escribimos en la consola.
console.log("Hola Mundo");
- Ctrl C para salir.
- Ahora vamos a crear un archivo llamado hola.js con el contenido anterior, es decir:
console.log("Hola Mundo");
- Guardamos este archivo en la misma carpeta en la que se encuentre el node.exe
- lo ejecutamos directamente desde el símbolo de sistema mediante:
node hola.js
- Si escribes nodevars
- se adaptará las variables de entorno para poder lanzar node.exe desde cualquier directorio.
__________________________________________________________________________
- También se puede ejecutar desde el Git Bash.
Observa:
./node.exe server.js
____________________________________________
2.- Servidor Web.
- Creamos este archivo y lo guardamos en la misma carpeta en la que se encuentre node.exe
server.js |
var http = require("http");
function onRequest(request, response) {
console.log("Peticion Recibida.");
response.writeHead(200, {"Content-Type": "text/html"});
response.write("Hola Mundo");
response.end();
}
http.createServer(onRequest).listen(8888);
console.log("Servidor Iniciado.");
|
- Ejecutamos el archivo como indico en la siguiente imagen:
node server.js
- Ahora vamos a un navegador web y escribimos: 127.0.0.1:8888
- Ctrl C para salir del servidor.
________________________________________________________
- Otro ejemplo.
- En este caso el archivo index.js iniciará el servidor. Ejecutamos:
node index.js
server2.js |
var http = require("http");
var url = require("url");
function iniciar() {
function onRequest(request, response) {
var pathname = url.parse(request.url).pathname;
console.log("Petición para " + pathname + " recibida.");
response.writeHead(200, {"Content-Type": "text/html"});
response.write("Hola Mundo");
response.end();
}
http.createServer(onRequest).listen(8888);
console.log("Servidor Iniciado.");
}
exports.iniciar = iniciar;
|
index.js |
var server = require("./server2");
server.iniciar();
|
_________________________________________________________________________
- Este ejemplo consta de 4 archivos, obtendremos un formulario, escribimos algo en él y obtendremos una respuesta.
- de este tutorial: https://www.nodebeginner.org/index-es.html
node index.js
index.js |
var server = require("./server");
var router = require("./router");
var requestHandlers = require("./requestHandlers");
var handle = {}
handle["/"] = requestHandlers.iniciar;
handle["/iniciar"] = requestHandlers.iniciar;
handle["/subir"] = requestHandlers.subir;
server.iniciar(router.route, handle);
|
server.js |
var http = require("http");
var url = require("url");
function iniciar(route, handle) {
function onRequest(request, response) {
var dataPosteada = "";
var pathname = url.parse(request.url).pathname;
console.log("Peticion para " + pathname + " recibida.");
request.setEncoding("utf8");
request.addListener("data", function(trozoPosteado) {
dataPosteada += trozoPosteado;
console.log("Recibido trozo POST '" + trozoPosteado + "'.");
});
request.addListener("end", function() {
route(handle, pathname, response, dataPosteada);
});
}
http.createServer(onRequest).listen(8888);
console.log("Servidor Iniciado");
}
exports.iniciar = iniciar;
|
router.js |
function route(handle, pathname, response, postData) {
console.log("A punto de rutear una peticion para " + pathname);
if (typeof handle[pathname] === 'function') {
handle[pathname](response, postData);
} else {
console.log("No se ha encontrado manipulador para " + pathname);
response.writeHead(404, {"Content-Type": "text/html"});
response.write("404 No encontrado");
response.end();
}
}
exports.route = route;
|
requestHandlers.js |
var querystring = require("querystring");
function iniciar(response, postData) {
console.log("Manipulador de peticion 'inicio' fue llamado.");
var body = '<html>'+
'<head>'+
'<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />'+
'</head>'+
'<body>'+
'<form action="/subir" method="post">'+
'<textarea name="text" rows="2" cols="60"></textarea>'+
'<input type="submit" value="Submit text" />'+
'</form>'+
'</body>'+
'</html>';
response.writeHead(200, {"Content-Type": "text/html"});
response.write(body);
response.end();
}
function subir(response, dataPosteada) {
console.log("Manipulador de peticion 'subir' fue llamado.");
response.writeHead(200, {"Content-Type": "text/html"});
response.write("Tu enviaste el texto: : " +
querystring.parse(dataPosteada)["text"]);
response.end();
}
exports.iniciar = iniciar;
exports.subir = subir;
|
_______________________________________________________________________
3.- ESP32/ESP8266. Sensor de temperatura y humedad. Servidor Web Node.js. Gráfico en página web.
- Vamos a seguir este tutorial, lo puedes traducir con el traductor de Google.
https://iotmakervn.github.io/iot-starter-book/
- Funciona con el ESP32 y con el ESP8266 cambiando la línea que indico en el código.
- Se trata de que en el ESP32 tenemos un sensor de temperatura y humedad DHT-11, en mi ejemplo no he utilizado ese sensor, obtengo los valores de temperatura y humedad mediante números aleatorios. Cada 2 segundos se obtendrá ese par de valores y se enviará al servidor web creado en nuestro ordenador con Node.Js.
- El ESP32 enviará una petición de esta forma: http://192.168.1.40:8000/update?temp=30&humd=45
- El Servidor Web construido con Node.Js en nuestro ordenador (en mi caso 192.168.1.40), recibirá esa petición y guardará ese valor en la variable db[]
- Si vamos a un navegador web y escribimos la dirección del servidor, http://192.168.1.40:8000 obtendremos un gráfico en tiempo real de los valores entregados.
node server.js
- El ESP32 le envía cada 2 segundos al servidor esta llamada:
http://192.168.1.40:8000/update?temp=30&humd=45
- Observa la variable req_uri y client.print
- Es decir, le va enviando al Servidor Web temp y humd.
ESP32_Envia_a_NodeJS.ino |
#include <DHT.h> // Khai báo s? d?ng thu vi?n DHT
// #include <ESP8266WiFi.h> // Khai báo s? d?ng thu vi?n ESP8266WiFi.h d? thi?t l?p ch? d? HTTP client cho ESP8266
#include <WiFi.h> // ESP32
#define DHTPIN 4 // Chân d? li?u c?a DHT11 k?t n?i v?i GPIO4 c?a ESP8266
#define DHTTYPE DHT11 // Lo?i DHT du?c s? d?ng
DHT dht(DHTPIN, DHTTYPE);
WiFiClient client; // T?o 1 bi?n client thu?c ki?u WiFiClient
const char* ssid = "Nombre_WiFi"; // Tên m?ng Wifi du?c ch? d?nh s? k?t n?i (SSID)
const char* password = "Clave_WiFi"; // Password c?a m?ng Wifi du?c ch? d?nh s? k?t n?i
const char* server = "IP del servidor, por ejemplo 192.168.1.40"; // Ð?a ch? IP c?a máy khi truy c?p cùng m?ng WiFi
const int port = 8000; // Port c?a server dã m?
const int sendingInternval = 2 * 1000; // Bi?n c?p nh?t d? li?u sau m?i 2s
void setup() {
Serial.begin(115200);
dht.begin(); // Kh?i t?o DHT1 11 d? truy?n nh?n d? li?u
Serial.println("Connecting");
// Thi?t l?p ESP8266 là Station và k?t n?i d?n Wifi. in ra d?u `.` trên terminal n?u chua du?c k?t n?i
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
Serial.print(".");
delay(100);
}
Serial.println("\r\nWiFi connected");
}
void loop() {
// Ð?c gía tr? nhi?t d? (d? C), d? ?m. Xu?t ra thông báo l?i và thoát ra n?u d? li?u không ph?i là s?
float temp = dht.readTemperature();
float humi = dht.readHumidity();
temp = random(0,50); // ALEATORIOS
humi = random(0,100); // ALEATORIOS
if (isnan(temp) || isnan(humi)) {
Serial.println("Failed to read from DHT sensor!");
return;
}
if (client.connect(server, port)) { // Kh?i t?o k?t n?i d?n server thông qua IP và PORT dã m?
//---------------------------------------------------------------------------------------
String req_uri = "/update?temp=" + String(temp, 1) + "&humd=" + String(humi, 1);
client.print("GET " + req_uri + " HTTP/1.1\n" + "Host: "+ server +"\n" + "Connection: close\n" + "Content-Length: 0\n" +"\n\n");
//---------------------------------------------------------------------------------------
// temp, humi chuy?n t? d?nh d?ng float sang d?nh d?ng string và in ra màn hình serial // terminal trên Arduino.
Serial.printf("Nhiet do %s - Do am %s\r\n", String(temp, 1).c_str(), String(humi, 1).c_str());
}
client.stop(); // Ng?t k?t n?i d?n server
delay(sendingInternval);
}
|
- El servidor toma llamada:
http://192.168.1.40:8000/update?temp=30&humd=45
actualiza la variable db [].
server.js |
//---------------------------------------------------------------------------------------------
var fs = require('fs');
var url = require('url');
var http = require('http');
var querystring = require('querystring');
var db = []; //database
//---------------------------------------------------------------------------------------------
// function g?i yêu c?u(response) t? phía server ho?c nh?n yêu c?u (request) c?a client g?i lên
function requestHandler(request, response) {
// Gi? s? d?a ch? nh?n du?c http://192.168.1.7:8000/update?temp=30&humd=40
var uriData = url.parse(request.url);
var pathname = uriData.pathname; // /update?
var query = uriData.query; // temp=30.5&hum=80
var queryData = querystring.parse(query); // queryData.temp = 30.5, queryData.humd = 40
//-----------------------------------------------------------------------------------------
if (pathname == '/update') {
var newData = {
temp: queryData.temp,
humd: queryData.humd,
time: new Date()
};
db.push(newData);
console.log(newData);
response.end();
//-----------------------------------------------------------------------------------------
} else if (pathname == '/get') {
response.writeHead(200, {
'Content-Type': 'application/json'
});
response.end(JSON.stringify(db));
db = [];
//-----------------------------------------------------------------------------------------
} else {
fs.readFile('./index.html', function(error, content) {
response.writeHead(200, {
'Content-Type': 'text/html'
});
response.end(content);
});
}
//-----------------------------------------------------------------------------------------
}
var server = http.createServer(requestHandler);
server.listen(8000);
console.log('Server listening on port 8000');
|
- El archivo index.html presenta el gráfico.
index.html |
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>DHT11</title>
<!-- Nhúng file Javasript t?i du?ng d?n src d? có th? xây d?ng 1 graph -->
<script type="text/javascript" src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
</head>
<body>
<h1> 1. THONG SO NHIET DO, DO AM</h><br>
<h2> Temprature</h2> <input type="text" size="6" id="temp">°C<br>
<h2> Humidity</h2> <input type="text" size="6" id="humd">%<br>
<h1> 2. DO THI</h1><br>
<!-- thi?t l?p kích thu?c cho graph thông qua id ChartContainer dã thi?t l?p ? trên -->
<div id="ChartContainer" style="height: 300px; width:80%;"></div>
<script type="text/javascript">
function httpGetAsync(theUrl, callback) {
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
callback(JSON.parse(xmlHttp.responseText));
}
xmlHttp.open("GET", theUrl, true); // true for asynchronous
xmlHttp.send(null);
}
window.onload = function() {
var dataTemp = [];
var dataHumd = [];
var Chart = new CanvasJS.Chart("ChartContainer", {
zoomEnabled: true, // Dùng thu?c tính có th? zoom vào graph
title: {
text: "Temprature & Humidity" // Vi?t tiêu d? cho graph
},
toolTip: { // Hi?n th? cùng lúc 2 tru?ng giá tr? nhi?t d?, d? ?m trên graph
shared: true
},
axisX: {
title: "chart updates every 2 secs" // Chú thích cho tr?c X
},
data: [{
// Khai báo các thu?c tính c?a dataTemp và dataHumd
type: "line", // Ch?n ki?u d? li?u du?ng
xValueType: "dateTime", // Cài d?t ki?u giá tr? t?i tr?c X là thu?c tính th?i gian
showInLegend: true, // Hi?n th? "temp" ? m?c chú thích (legend items)
name: "temp",
dataPoints: dataTemp // D? li?u hi?n th? s? l?y t? dataTemp
},
{
type: "line",
xValueType: "dateTime",
showInLegend: true,
name: "humd",
dataPoints: dataHumd
}
],
});
var yHumdVal = 0; // Bi?n luu giá tr? d? ?m (theo tr?c Y)
var yTempVal = 0; // Bi?n luu giá tr? nhi?t d? (theo tr?c Y)
var updateInterval = 2000; // Th?i gian c?p nh?t d? li?u 2000ms = 2s
var time = new Date(); // L?y th?i gian hi?n t?i
var updateChart = function() {
httpGetAsync('/get', function(data) {
// Gán giá tr? t? localhost:8000/get vào textbox d? hi?n th?
document.getElementById("temp").value = data[0].temp;
document.getElementById("humd").value = data[0].humd;
// Xu?t ra màn hình console trên browser giá tr? nh?n du?c t? localhost:8000/get
console.log(data);
// C?p nh?t th?i gian và l?y giá tr? nhi?t d?, d? ?m t? server
time.setTime(time.getTime() + updateInterval);
yTempVal = parseInt(data[0].temp);
yHumdVal = parseInt(data[0].humd);
dataTemp.push({ // c?p nhât d? li?u m?i t? server
x: time.getTime(),
y: yTempVal
});
dataHumd.push({
x: time.getTime(),
y: yHumdVal
});
Chart.render(); // chuy?n d?i d? li?u c?a c?a graph thành mô hình d? h?a
});
};
updateChart(); // Ch?y l?n d?u tiên
setInterval(function() { // C?p nh?t l?i giá tr? graph sau th?i gian updateInterval
updateChart()
}, updateInterval);
}
</script>
</body>
</html>
|
_______________________________________________
2.- El cliente ESP32 envía valores cada 2 segundos a Android, mediante el servidor de Node.js y la nueva página index.html.
ESP32 -------> App
p9A0i_esp32_nodejs.aia
- EL ESP32 seguirá enviado los valores al servidor cada 2 segundos mediante:
http://192.168.1.40:8000/update?temp=30&humd=45
- Esos valores llegarán a la nueva página index.html y esta página la pasará a App Inventor mediante
window.AppInventor.setWebViewString("" + temp_humi);
- App Inventor los muestrará en un gráfico.
- Enviaremos la variable temp_humi, por ejemplo: 23.0,87.0
- El código del ESP32 es el mismo que hemos visto en el apartado anterior: ESP32_Envia_a_NodeJS.ino
index.html |
<!DOCTYPE html>
<html><head> <meta charset="UTF-8"><title>DHT11</title></head>
<body>
<script type="text/javascript">
function httpGetAsync(theUrl, callback) {
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
callback(JSON.parse(xmlHttp.responseText));
}
xmlHttp.open("GET", theUrl, true); // true for asynchronous
xmlHttp.send(null);
}
window.onload = function() {
var updateInterval = 2000;
var time = new Date();
var update = function() {
httpGetAsync('/get', function(data) {
var temp_humi = data[0].temp + "," + data[0].humd;
window.AppInventor.setWebViewString("" + temp_humi);
time.setTime(time.getTime() + updateInterval);
});
};
update();
setInterval(function() {
update()
}, updateInterval);
}
</script>
</body>
</html>
|
_______________________________________________
- Diseño.
- Android tomará y mostrará esos valores, además dibujará un gráfico dinámico de la humedad.
_______________________________________________
- Bloques.
_______________________________________________
3.- Android mediante el VisorWeb envía valores al ESP32 que será cliente del Node.js.
App -------> ESP32
p9A0i_esp32_nodejs_Envia.aia
- Ahora desde la aplicación enviaremos dos número. Llegarán al Servidor Web del Node.js.
- Por otra parte cada 5 segundo el ESP32 consultará al Servidor Web, mediante esta línea.
client.print(String("GET ") + url + " HTTP/1.1\r\n" + "Host: " + host + "\r\n" + "Connection: close\r\n\r\n");
- En el caso de que hallamos enviando los dos números desde la aplicación, obtendremos una información de esta forma:
[{"temp":"30","humd":"45","time":"2021-07-31T17:32:17.391Z"}]
- Esto lo obtendremos mediante "/get", consulta el código del ESP32 y del server.js
- La información viene en Json, la decodificamos mediante esta librería (ArduinoJson versión 5): ArduinoJson.zip
- También podemos enviar los dos números directamente desde un navegador, escribe en un navegador:
192.168.1.40:8000/update?temp=30&humd=45
- Al escribir esa dirección en un navegador web, enviamos ese par de valores.
- Esa información llegará al Servidor y de éste al ESP32, se mostrará en el Monitor Serie.
__________________________________________________________________
- Código para el ESP32 o ESP8266
ESP32_recibe_de_NodeJs.ino |
// Juan A. Villalpando
// http://kio4.com/arduino/117_Wemos_NodeJs.htm
// #include <ESP8266WiFi.h>
#include <WiFi.h>
#include <ArduinoJson.h>
const char* ssid = "Nombre_Red_Wifi";
const char* password = "Clave_Wifi";
const char* host = "192.168.1.40";
void setup(){
Serial.begin(115200);
delay(10);
// Conecta a la red wifi.
Serial.print("Conectando con ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("Conectado con WiFi.");
// Esta es tu IP
Serial.print("Tu IP: ");
Serial.print(WiFi.localIP());
}
void loop(){
Serial.print("Conectando con ");
Serial.println(host);
// Cliente
WiFiClient client;
const int httpPort = 8000;
if (!client.connect(host, httpPort)) {
Serial.println("Fallo en la conexión.");
return;
}
// Linea de petición
String url = "/get";
Serial.println(url);
// Esto es lo que se enviará al servidor.
client.print(String("GET ") + url + " HTTP/1.1\r\n" +
"Host: " + host + "\r\n" +
"Connection: close\r\n\r\n");
unsigned long timeout = millis();
while (client.available() == 0) {
if (millis() - timeout > 5000) {
Serial.println(">>> Rebasado 5 segundos.");
client.stop();
return;
}
}
// Lee todas las líneas que ha enviado el servidor.
while(client.available()) {
String lineas = client.readStringUntil('\r');
if (lineas.indexOf("[{") != -1) { // Linea que contiene [{.
Serial.println(lineas);
String json = lineas.substring(2,lineas.length()-1); // Elimina [ ]
Serial.println(json);
StaticJsonBuffer<200> jsonBuffer;
JsonObject& deco = jsonBuffer.parseObject(json);
if(!deco.success()) {Serial.println("parseObject() failed");}
else { String temp = deco["temp"];
String humd = deco["humd"];
String tempo = deco["time"];
Serial.println(temp);
Serial.println(humd);
Serial.println(tempo);
}
}
}
Serial.println("Conexión cerrada.");
}
|
_______________________________________________
- Diseño.
_______________________________________________
- Bloques.
_______________________________________________
4.- Guardar la información en un archivo.
- Vamos a guardar la información en el archivo datos.txt, para eso cambiamos esta parte del server.js
cambio en server.js |
//-----------------------------------------------------------------------------------------
if (pathname == '/update') {
var newData = {
temp: queryData.temp,
humd: queryData.humd,
time: new Date()
};
db.push(newData);
console.log(newData);
response.end();
fs.appendFile('datos.txt', JSON.stringify(newData) + '\n', function (err) {
if (err) return console.log(err);
console.log('Guardado en datos.txt');
});
//-----------------------------------------------------------------------------------------
|
____________________________________________
5.- App Inventor. Web server. Script. Teorema de Pitágoras.
p9A0i_esp32_nodejs_pitagoras.aia
- En este tutorial de App Inventor vimos cómo calcular el Teorema de Pitágoras mediante un JavaScript.
- Observa que el archivo pitagoras.htm se encuentra en el asset.
- Ahora vamos a copiar ese archivo en el directorio donde se encuentra el node.exe
pitagoras.htm |
<!DOCTYPE html>
<html>
<head><meta charset="utf-8"></head><body>
<script>
datos = window.AppInventor.getWebViewString(); // Entrada de datos.
datos = datos + ":";
catetos = datos.split(":");
cateto1 = catetos[0];
cateto2 = catetos[1];
hipotenusa = Math.sqrt(Math.pow(cateto1, 2) + Math.pow(cateto2, 2)) ;
window.AppInventor.setWebViewString("" + hipotenusa); // Respuesta a CadenaDeWebView
</script>
</body></html>
|
- También cambiaremos el server.js, añadimos estas lineas:
cambio en server.js |
//-----------------------------------------------------------------------------------------
} else if (pathname == '/pitagoras') {
fs.readFile('./pitagoras.htm', function(error, content) {
response.writeHead(200, {
'Content-Type': 'text/html'
});
response.end(content);
});
//-----------------------------------------------------------------------------------------
|
_______________________________________________
- Diseño.
_______________________________________________
- Bloques.
- Fíjate que llamamos a: http://192.168.1.40:8000/pitagoras
____________________________________________
6.- Ejecutar un archivo por lote enviando la orden desde la aplicación. Apagar el ordenador.
- Vamos a ejecutar un archivo por lotes de Windows, un .bat.
- Vamos a ejecutar un apagado del ordenador, mediante esta orden: shutdown /s /f /t 0
- Crearemos este archivo por lotes llamado apagar.bat y lo copiaremos en el directorio donde se encuentra el node.exe
apagar.bat |
shutdown /s /f /t 0
|
- Modificaremos el código del server.js copiando estas líneas
cambio en server.js |
//-----------------------------------------------------------------------------------------
} else if (pathname == '/apaga') {
const { exec, spawn } = require('child_process');
exec('apagar.bat, (err, stdout, stderr) => {
if (err) {
console.error(err);
return;
}
console.log(stdout);
});
//-----------------------------------------------------------------------------------------
|
- Desde App Inventor o directamente desde un navegador escribimos:
http://192.168.1.40:8000/apaga
- esto ejecutará el archivo apagar.bat
- Cancelar el apagado, en vez de poner un tiempo 0 podemos poner, por ejemplo:
shutdown /s /f /t 30
- Esto comenzará el apagado dentro de 30 segundos.
- Si antes del comienzo escribimos:
shutdown -a
se cancelará la orden de apagado.
_____________________
- Puedes crear otros archivos por lotes, por ejemplo este ejecutaría el Bloc de notas.
____________________________________________
7.- Enviar correo mediante Gmail.
https://www.w3schools.com/nodejs/nodejs_email.asp
- Enviar un correo desde nuestra cuenta de Gmail a otro usuario.
- Instalamos:
npm install
nodemailer
servercorreo.js |
var nodemailer = require('nodemailer');
var transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: 'mi_correo@gmail.com',
pass: 'contraseña'
}
});
var mailOptions = {
from: 'mi_correo@gmail.com',
to: 'enviaraeste@yahoo.com',
subject: 'Sending Email using Node.js',
text: 'That was easy!'
};
transporter.sendMail(mailOptions, function(error, info){
if (error) {
console.log(error);
} else {
console.log('Email sent: ' + info.response);
}
});
|
- Debemos que permitir en Acceso de aplicaciones poco seguras en Gmail.
https://myaccount.google.com/lesssecureapps
____________________________________________
8.- Tutoriales.
- Chat con ESP32: https://robotzero.one/node-js-chat-server-esp32
- ESP32 lowjs: https://codemain.es/esp32-lowjs-javascript/ lowjs es un Node.js para el ESP32
- Tutorial: https://www.w3schools.com/nodejs/default.asp
MySQL: https://www.w3schools.com/nodejs/nodejs_mysql.asp
Subir archivo con formidable: https://www.w3schools.com/nodejs/nodejs_uploadfiles.asp
- Instalamos:
npm install formidable
serverformidable.js |
var http = require('http');
var formidable = require('formidable');
var fs = require('fs');
http.createServer(function (req, res) {
if (req.url == '/fileupload') {
var form = new formidable.IncomingForm();
form.parse(req, function (err, fields, files) {
var oldpath = files.filetoupload.path;
var newpath = 'C:/Users/juan/' + files.filetoupload.name;
fs.rename(oldpath, newpath, function (err) {
if (err) throw err;
res.write('File uploaded and moved!');
res.end();
});
});
} else {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write('<form action="fileupload" method="post" enctype="multipart/form-data">');
res.write('<input type="file" name="filetoupload"><br>');
res.write('<input type="submit">');
res.write('</form>');
return res.end();
}
}).listen(8080);
|
____________________________________________
9.- Instalar Node.Js en Android con Termux.
- Vamos a instalar el Shell Termux, lo bajado de la Play de Google.
- Una vez instalado escribirmos:
pkg install nodejs-lts
- Para comprobar que se ha instalado escribimos:
node -v
- El directorio home es
/data/data/com.termux/files/home
en
/data/data/com.termux/files/usr/bin se encuentra el node
____________________________________________
10.- Servidor web con Express.
- Express es un frame para crear servidores web:
https://blog.back4app.com/es/diferencias-entre-express-js-y-node-js/
npm install express
- Se creará un directorio en npm
server.js |
const express = require('express');
const port = 8000;
const app = express();
app.get('/hola', (req, res) => {
res.send('Hola mundo');
});
app.listen(port, () => console.log(`Servidor iniciado en el puerto ${port}`) );
|
- En un navegador escribimos 127.0.0.1/hola y obtendremos el mensaje.
- Otros comando de express
res.send()
res.sendFile()
res.sendStatus()
res.render()
res.json()
res.jsonp()
res.set()
- Otro ejemplo de Express.
app.js |
const path = require('path');
const express = require('express');
const app = express();
app.use(express.static(path.join(__dirname, '')))
app.get('/', (req, res) => {
res.sendFile(`${__dirname}/index.html`);
});
app.listen(3333, () => {
console.log('Application listening on port 3333!');
});
|
index.html |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="/app.js"></script>
<link rel="stylesheet" href="/styles.css">
<title>My server</title>
</head>
<body>
<h1>My server</h1>
<p>Server built with Node.js and Express</p>
</body>
</html>
|
styles.css |
html {
background-color: blue;
}
|
_______________________________
|