acceder a node.js desde el exterior

me llamo Jesús, tengo en mi pc instalado node.js, tambien el servidor de php xampp. Mi router lo tengo configurado para poder acceder a mi pc con mi ip publica desde un dispositivo exterior como el móvil. Actualmente puedo acceder desde el exterior usando el servidor xampp.

Me interesa muchísimo saber como se puede hacer lo mismo con node.js, de esta manera no tengo que contratar ningun hosting para hacer pruebas.

Aunque mi ip es dinámico me sirve para testear.

Muchas gracias por vuestra ayuda

What version of Node.js can I use if I’m stuck on SPFx v.1.1.0 (SP 2016)?

I’m stuck on SharePoint 2016 for the time being, and I know that means I’m stuck using SPFx v.1.1.0.

However, I’m not sure what that means in terms of what version of Node.js to use.

I have some notes from a conference that say to use Node LTS v.8, but my notes are not clear on whether that means it must be exactly v.8, or at a minimum v.8.

I’m asking because I have a non-SharePoint project that is requiring Node LTS v.10, and I’m trying to figure out if I can just upgrade to Node v.10, or if I’ll have to install NVM so I can switch between 8 and 10 depending on what I’m working on.

Will SPFx v.1.1.0 work with Node LTS v.10?

PHP stuff requests on Node.js based web app?

We have a Node.js based web application, that has routes like:

myapp.com/posts/[postId]

We tracked strange requests, which lead to 404 on this routes. The requests were to routes like:

/posts/phpinfo.php /posts/.user.ini /posts/info.php3 /posts/phptest.php 

Neither we’re using PHP nor do i know anything about it…

To me it seems that a crawler/bot is requesting these routes, using some PHP related stuff as postIds which makes no sense (to me)…

Is this legit, though useless, or a security related issue?

What could cause this?

How To Set Up a Node.js Application for Production on a Debian 9 VPS

In this tutorial, we will create a simple Node.js application and put it into a production ready environment on Debian 9, “Stretch”.

  • To make the app accessible from your browser, we’ll use Nginx as a reverse proxy. Nginx is a fast and versatile web server, and can also be used as a Load Balancer.
  • To make the access to the app secure, we’ll use Certbot to install Let’s Encrypt certificates. Then, we’ll be able to use HTTPS requests instead of unsecure HTTP requests.
  • Finally, we will make sure that the app is running continually, by turning it into a service with a special NPM package called PM2. PM2 will daemonize the Node.js app and run it in the background, even after system crashes or reboots.

 

What We Are Going To Cover

  • Install Nginx
  • First install firewall-cmd, then change its rules to enable Nginx
  • Install the latest version of Node.js
  • Add NPM packages for the app that we are making
  • Create the example app to show all characters in upper case
  • Configure Nginx as a reverse proxy
  • Install Let’s Encrypt certificates to serve HTTPS requests
  • Access the app from the browser
  • Install PM2, which is a production process manager for Node.js applications with a built-in traffic Load Balancer
  • Use PM2 to restart the Node.js app on every restart or reboot of the system

Prerequisites

We use Debian 9:

  • Starting with a clean VPS with
  • At least 512Mb of RAM and
  • 15Gb of free disk space.
  • You will need root user access via SSH
  • A domain name pointed to your server’s IP address (it can also be a subdomain) using A records at your DNS service provider
  • We use nano as our editor of choice, and you can install it with this command:
sudo apt install nano 

Step 1: Install Nginx From a Repository

After you have logged in as a root user, install Nginx. Let’s refresh the cache and start the installation:

sudo apt update sudo apt upgrade -y 

Now install Nginx:

sudo apt install nginx -y 

In the browser, go to address

http://YOUR_DOMAIN/ 

and verify that Nginx is running:

Step 2: Change Firewall Rules to Enable Nginx

On Debian, the iptables firewall is installed by default, but we prefer ufw, the uncomplicated firewall. First install it:

sudo apt install ufw 

List all the port profiles ufw already knows about:

sudo ufw app list 

That is quite a list:

There are three options fo Nginx:

  • Nginx Full: Opens ports 80 and 443 for normal, unencrypted web traffic and TLS/SSL for encrypted traffic, respectively.
  • Nginx HTTP: Only port 80 (normal, unencrypted web traffic)
  • Nginx HTTPS: Only port 443 (TLS/SSL encrypted traffic)

In theory, we should use the most restrictive type of access. However, there is a possibility that someone will use a HTTP request instead of a HTTPS, so we enable the full option:

sudo ufw allow 'Nginx Full' 

Node.js apps require a port that is not used by the system, but is dedicated to that one app only. In our examples, we might use ports such as 3000, 8080 and so on, so we need to declare them explicitly, otherwise your app won’t run.

Here is a list of ports and feel free to add any other that your host requires for the normal functioning of the system:

sudo ufw allow ssh sudo ufw allow http sudo ufw allow https sudo ufw allow 20/tcp sudo ufw allow 21/tcp sudo ufw allow 3000 sudo ufw allow 8080 sudo ufw allow 'Nginx Full' sudo ufw enable 

WARNING:

Always execute ufw commands with ssh, http, https and so on, otherwise you will NOT be able to log back into your VPS server!

To see the changes, run:

sudo ufw status 

Step 3: Install Latest Node.js

Execute this series of commands to install node.js:

cd /tmp sudo apt install curl -y sudo curl -sLO https://deb.nodesource.com/setup_12.x sudo bash setup_12.x sudo apt-get install gcc g++ make apt install nodejs sudo nodejs -v 

The script sets up the proper Debian package repositories and also installs gcc, g++ and make. They may be required by some Node.js packages during their installation to compile their parts written in C or C++. Finally, it inspects the Node.js version:

Node.js version

It shows v12.3.1, which was the actual version of at the time of this writing. If it shows an error, double check the commands you entered against the ones shown above.

Step 4: Adding NPM Packages

We of course know what packages our Node.js app will need, so we install the required npm packages in advance. First we install prerequisite packages for NPM:

sudo apt install build-essential libssl-dev 

With that, we will be able to install all other packages out there.

Since our app will turn any input into uppercase letters, we install a package for that:

npm install upper-case 

Most Node.js apps will now use Express.js, so let’s install that as well:

npm install --save express 

Execute this command as well:

npm install -g nginx-generator 

It will globally install an NPM package to generate the reverse proxy config for Nginx. We will apply it after the app is running on port 8080.

Step 5: Creating The App

Open a file named uppercase-http.js for editing:

nano uppercase-http.js 

Add the following lines:

var http = require('http'); var uc = require('upper-case'); console.log('starting...'); http.createServer(function (req, res) {   console.log('received request for url: ' + req.url);   res.writeHead(200, {'Content-Type': 'text/html'});   res.write(uc(req.url + '\n'));   res.end(); }).listen(8080); 

Save and close the file.

The HTTP server will listen to port 8080. You can specify any other port that you like, provided that it will be free when the app is running (and that you have previously opened access to it in ufw).

Run the app:

node uppercase-http.js 

You will see the following message:

starting... 

Node.js app starting

To test it, fire up another terminal, connect to your VPS as root via SSH and curl localhost:8080:

curl localhost:8080 curl localhost:8080/test 

The program correctly converted the path to uppercase. If you look at the server app itself, it showed a status message for both requests:

received request for url: / received request for url: /test 

App server messages

Now you have two windows, one with an active app and the other with the curl statement. From now on, enter commands only into the second window, otherwise you would have to stop the app and then the rest of the procedure would make no sense.

Step 6: Configure Nginx as Reverse Proxy

Let’s now access this app from your web browser. Empty the default file in folder /etc/nginx/sites-available/ with the following two commands:

rm /etc/nginx/sites-available/default sudo nano /etc/nginx/sites-available/default 

That file has to be empty in order for Nginx to read files in the /etc/nginx/sites-enabled/ folder. Enter one space into this otherwise empty file, save and close it.

Now, we will use the NPM package nginx-generator that we have installed earlier in this tutorial, to generate files that will tell Nginx to act as a reverse proxy. In the command line, execute the following:

nginx-generator \       --name site_nginx \       --domain YOUR_DOMAIN \       --type proxy \       --var host=localhost \       --var port=8080 \       /etc/nginx/sites-enabled/site_nginx 

Replace YOUR_DOMAIN with your domain before running this command.

That command creates a file called site_nginx and puts it into the directory /etc/nginx/sites-enabled/. (We could have used any other file name instead of site_nginx.)

We can see it with this command:

sudo nano /etc/nginx/sites-enabled/site_nginx 

Test the configuration:

sudo nginx -t 

and if everything is OK, restart Nginx:

systemctl restart nginx 

In your browser, go to address

http://YOUR_DOMAIN/test 

and the result should be

/TEST 

Step 7: Securing Your Site To Serve Only HTTPS

Our goal is to run a production version of a Node.js app, which means we must serve it for HTTPS requests. If you have a domain name and DNS records properly set up to point to your VPS, you can use certbot to generate Let’s Encrypt certificates. This means that you will always access the app as well as the rest of your domain, via HTTPS.

We will folow the original documentation to install Let’s Encrypt. Choose Nginx for software and Debian 9 (stretch) for System – it should look like this:

Certbot Certbot Site

Certbot for Debian comes from the Backports repo so let us open the sources list

nano /etc/apt/sources.list.d/nginx.list 

and enter the following line into that file:

deb http://deb.debian.org/debian stretch-backports main 

Run

apt-get update 

and install backports:

sudo apt-get install certbot python-certbot-nginx -t stretch-backports 

Finally, activate it with:

sudo certbot --nginx 

What certbot will ask you will depend on the previous events. If you are installing it for the fist time, it will ask for an emergency email address, then several less important questions and finally – do you want to redirect all HTTP traffic to HTTPS? Select 2 to confirm this redirection, and you’re all set!

Test the configuration:

sudo nginx -t 

and if everything is OK, restart Nginx again:

systemctl restart nginx 

In your browser, go to address

http://YOUR_DOMAIN/test 

and the result should be

/TEST 

Note that this address started with HTTP, but that it ended up as HTTPS.

Step 8: Install PM2

PM2 is a production process manager for Node.js applications. With PM2, we can monitor applications, their memory and CPU usage. It also provides easy commands to stop/start/restart all apps or individual apps.

Once the app is started through PM2, it will always be restarted after system crashes or restarts. In effect, it will “always be there”.

We use NPM to install PM2:

sudo npm install pm2@latest -g 

Option -g tells it install pm2 globally, meaning that we shall be able to run it from all paths in the system.

Let’s now run our application under PM2:

cd ~ pm2 start uppercase-http.js 

The output of PM2 can be spectacular when run for the first time, but we really need to concentrate on the rows about the app:

PM2 will use app name, and then show the id number of the app, mode, status, CPU usage and memory. If two or more apps are running in the background, they will all be presented in this table.

We can list the processes like this:

sudo pm2 list 

The following command

sudo pm2 show 0 

will show details of the app with ID of 0:

It is also possible to monitor CPU usage in real time:

sudo pm2 monit 

Other useful PM2 commands are stop, restart, delete.

What Can You Do Next

We have shown how to set up a Node.js app for a production environment, as a root user, on a Debian 9 VPS. You can study more about Nginx and add several sites on one VPS server, each with its own non-root user, listening on different ports and so on. As a Node.js programmer, you would also pay attention to debugging processes and other good practices – all of which is, however, out of scope of this article.

Dusko Savic is a technical writer and programmer.

duskosavic.com

The post How To Set Up a Node.js Application for Production on a Debian 9 VPS appeared first on Low End Box.

Error usando Angular.js – Node.js : Access to XMLHttpRequest at ‘.. ‘has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’

soy nuevo aprendiendo este stack MEAN, espero puedan ayudarme, llevo dias con esto y la verdad no puedo dormir bien por pensar tanto 🙁 .

Logre hacer una peticion get al sitio de JSON (https://jsonplaceholder.typicode.com/posts) y si me devolvio un JSON.

Pero tambien estoy intentando acceder a esta direccion (http://aplicaciones007.jne.gob.pe/srop_publico/Consulta/Afiliado/GetNombresCiudadano?DNI=47099414 ) y ya de por si le estoy agregando un parámetro que solicita, y en la web me devuelve datos(Un nombre y apellido). Pero cuando lo llamo desde angular me tira este error :

Access to XMLHttpRequest at ‘http://aplicaciones007.jne.gob.pe/srop_publico/Consulta/Afiliado/GetNombresCiudadano?DNI=47099414’ from origin ‘http://localhost:4200’ has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.


core.js:15724 ERROR HttpErrorResponse {headers: HttpHeaders, status: 0, statusText: “Unknown Error”, url: “http://aplicaciones007.jne.gob.pe/srop_publico/Consulta/Afiliado/GetNombresCiudadano?DNI=47099414”, ok: false, …} error: ProgressEvent {isTrusted: true, lengthComputable: false, loaded: 0, total: 0, type: “error”, …} headers: HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, headers: Map(0)} message: “Http failure response for http://aplicaciones007.jne.gob.pe/srop_publico/Consulta/Afiliado/GetNombresCiudadano?DNI=47099414: 0 Unknown Error” name: “HttpErrorResponse” ok: false status: 0 statusText: “Unknown Error” url: “http://aplicaciones007.jne.gob.pe/srop_publico/Consulta/Afiliado/GetNombresCiudadano?DNI=47099414” proto: HttpResponseBase


El codigo de mi servicio es :

 import { Injectable } from '@angular/core'; import {HttpClient}from '@angular/common/http' import { Persona } from '../modelos/persona';  @Injectable({   providedIn: 'root', }) export class PersonaService {    selectedPersona: Persona;   personas:Persona[];   readonly URL_API='http://localhost:3000/Inicio/Persona';   readonly URL_API_RENIEC='http://aplicaciones007.jne.gob.pe/srop_publico/Consulta/Afiliado/GetNombresCiudadano?DNI=47099414';   readonly URL_API_JSON='https://jsonplaceholder.typicode.com/posts';    constructor(private http: HttpClient) {      this.selectedPersona=new Persona();   }    getDataJson(){     return this.http.get(this.URL_API_JSON)   }    getDniPersona(){     return this.http.get(this.URL_API_RENIEC)   }  }  

Y en mi componente ts :

ngOnInit() {      this.personaService.getDataJson() //Obtener los datos de "https://jsonplaceholder.typicode.com/posts"     .subscribe(datos=>{       console.log(datos);     });       this.personaService.getDniPersona() //Obtener los datos de "aplicaciones007.jne.gob.pe/srop_publico/Consulta/Afiliado/GetNombresCiudadano?DNI=47099414"     .subscribe(datos=>{       console.log(datos);     }); } 

Por favor ayúdenme, gracias de antemano.

NODE.js com socket e MySql

estou com um problema com o node, acredito que deve ser algo relacionado a callback´s, porém não tenho certeza, mais enfim, meu problema se resuma basicamente em puxar os dados de um banco MySql, esses dados serão armazenados em uma variável chamada msg. Meu código completo é este:

        const express = require('express');         const path = require('path');         const app = express();         const server = require('http').createServer( app );         const io = require('socket.io')(server);         const mysql = require('mysql');          // conexao com o banco de dados          var con = mysql.createConnection({         host: "localhost",         user: "root",         password: "",         database: "dados_users"         });           app.use(express.static(path.join(__dirname,'public')));         app.set('views',path.join(__dirname,'public'));           app.engine('html',require('ejs').renderFile);         app.set('view engine','html');          app.use('/', ( request , res ) => {             res.render('index.html');         });          let msg =[];            io.on('connection', socket => {          //este select deve retornar as mensagens que estão no banco para a          //variavel msg         // con.connect(function(err) {         //     con.query('SELECT * FROM dados', function(err, rows, fields) {         //         if (err) throw err;         //           msg = rows;         //     });         // });          socket.emit('msg_existentes',msg);    //retorna dados earmazenados na variavel msg          socket.on('recebe_do_front', data => {            console.log(msg);          // con.connect(function(err) {         //     var sql = "INSERT INTO dados (nome, msg) VALUES ('"+data.nome+"', '"+data.msg+"')";         //     con.query(sql, function (err, result) {         //     if (err) throw err;         //         console.log("1 record inserted");         //     });         // });          msg.push( data );     //manter msg na section da pagina         socket.broadcast.emit('envia_para_usuario', data);   //retorna msg do canudo      }); }); server.listen(3001); 

A função que não esta fazendo a parte dela é a função de [ select ], esta abaixo:

   //este select deve retornar as mensagens que estão no banco para a    //variavel msg   con.connect(function(err) {        con.query('SELECT * FROM dados', function(err, rows, fields) {            if (err) throw err;                  msg = rows;        });     }); 

então é isso, quando é executado o programa, ele trás a variável msg vazia. Desde já Muito Obrigado!

How to scale complex node.js application

Imagine a large node.js app with a multi-purpose api for mobile and frontend with a serving static files, with a websocket server, lot of cron jobs and workers. Basically I can horizontally or vertically scale a whole app, use a load balancer and so on.

But from a perspective of a business logic, whole app is one big “bundle” where some parts are used more than others, also some parts have bigger impact on a performance of app than another. For example, mobile API may be used 100x more than some cron which starts 1 time per hour to make some cleanup. So is it necessary to scale whole app?

Isn’t it better to scale app to separate modules and scale only needed? For example

  • mobile api
  • FE api
  • crons and workers
  • websocket
  • whatever…

If so, what is proper way to handle business logic? There is a parts of code I would need in every submodule of application, for example database models, migrations (seeders?), maybe I would need some general functionality, like some specific utils functions or enum definitions. So I can create git submodules for them, but there is risk it will be too much complex to handle 4-6 git repositories with a 2-4 git submodules and handle whole app in multiple environments (dev, stage, uat, prod). Are there some others caveats of this approach? Or is it unusable?

I dived into waters of internet and searched for some resources for example node.js best practice, scaling node.js, scaling node.js, good scaling practice but it not fully answered all my questions.

React Native não inicia aplicação devida a falta de memoria no Node.js

FATAL ERROR: Zone Allocation failed – process out of memory (erro descrito) Bom, finalmente consegui instalar e configurar o ambiente de de desenvolvimento do React Native, porém ao dar run-android o cmd do node exibe uma mensagem de falta de memoria (meu notebook tem apenas 4GB de RAM), resultando em fechar o cmd do node e assim dando erro na aplicação android rodando no emulador.Já estou achando que é impossivel desenvolver em React com 4GB de RAM apenas. FATAL ERROR: Zone Allocation failed – process out of memory (erro descrito)node

Your first Node.js server

In this article, I want to tell you how you can start a simple Node.js HTTP server and begin processing requests.

The HTTP module for your Node.js server
When you start creating HTTP-based applications in Node.js, the built-in HTTP/HTTPS modules are the ones you will interact with.

Now, let’s build your first Node.js HTTP server! We will need to require the HTTP module and bind our server to the port 3000.

// content of index.js const http = require(‘http’)…

Your first Node.js server