linux – Run NodeJS server through SSH without hanging from disconnect

I have a NodeJS server on a virtual machine. I connect to the machine through SSH and leave the server running with:

npm start &

If I disconnect with Ctl-D, the server keeps running. If my internet drops and the connection fails, the server also stops. Why does this happen, and how can I leave the server running without it dropping because of the internet disconnection?

mysql – PHP ou Node.JS?

mysql – PHP ou Node.JS? – Stack Overflow em Português

javascript – How to check whether the user completed his missions? (Web Development Angular & nodejs)

I am working on a coding/gaming application, (a one just like coding game).
I am currently stuck in the daily missions part.

So, the user receivers everyday some missions, (eg; solving a problem, following another user, completing a quizz, …) that he has to complete.

The problem is the I didn’t know how to listen for mission Completion?
How will I know whether the user completed his missions or not?
What’s the best approach to implementing such a task?

Here’s a solution I thought of, however, I highly doubt that it is good:

Everytime the user completes a certain task I check whether he had that task as a daily mission, if positive, I’ll mark that mission as complete.
Eg;

onProblemSolve(){
   const missions = this.currentUser.getMissions();
   if(missions.contains('problemSolving')) {
       this.markMissionAsComplete();
   }
}

If you have any articles or tutorials that could clarify this, that would be a huge help

Thank you very much

node.js – Atualizar array posições especificas usando mongodb com ou sem Mongoose!

Tenho a seguinte situação!

const meuModel = new mongoose.Schema({

  nome: { type: String, required: (true, 'Nome') },
  
  links:{type : Array,},
}) 

Links é um array de objetos!

links ({url:link, clicks:0},{url:link1, clicks:0},{url:link2, clicks:0})

Eu preciso fazer update especifico. Sem nunca mudar os clicks, nem mexer neles!

links ({url:link, clicks:4},{url:novoLink, clicks:0},{url:link2, clicks:5},{url:novoLink2, clicks:0})

eu quero permitir o usuário modificar os Links como quiser. Mas os clicks sempre serão via sistema.

Meu problema esta me salvar isso no mongo!

teste = await MeuModel.findOneAndUpdate({
          _id
        },{$inc: {
          "links.0.url":'novolink', 
          "links.1.url": 'linkantigo', 
          "links.2.url": 'novo link se for novo',   
      }}

Isso não funciona!
Pois quer mudar uma posição, só quando viver do front algo novo!
Se o usuário mudou 3 links, eles devem ser salvos!

“$set” não aceita que eu percorra o array para modificar somente onde for preciso!
“$set” só permite mudança de 1 posição especifica

await meuModel.findOneAndUpdate({
          _id
        },{ 
          "$set": {(`links.$(outer).url`): 'novoLink'} 
        },
        { 
          "arrayFilters": ({ "outer.url":'antigoLink'})
        })

$set com arrayFilters só aceita uma condição para muitos ou apenas 1.

Quero poder mandar salvar o array todo de uma vez, com as modificações apenas dos links, se ela existirem!

node.js – Connect nodemailer to mr form

I have a mail.js file that when run independently sends me a mail. And I have a form. I want to send mail to the email id that fils the form. How can I do that? I am not able to connect these two.

Where and how do I add mail.send();? And how to add variable email if both of these codes are in different files?

Also my html is in index.html

Thank you!!

index.js

var express = require("express")
var bodyParser = require("body-parser")
var mongoose = require("mongoose")


const app = express()

app.use(bodyParser.json())
app.use(express.static('public'))
app.use(bodyParser.urlencoded({
    extended: true
}))

mongoose.connect('mongodb://localhost:27017/mydb123', {
    useNewUrlParser: true,
    useUnifiedTopology: true
});

var db = mongoose.connection;

db.on('error', () => console.log("Error in Connecting to Database"));
db.once('open', () => console.log("Connected to Database"));





app.post("/sign_up", (req, res) => {
    // var name = req.body.name;
    var email = req.body.email;

    // var phno = req.body.phno;
    // var password = req.body.password;
    // var initrefnum = req.body.demo;
    // var newrefnum = req.body.newdemo;

    console.log("step1");

    var data = {
        // "name": name,
        "email": email
        // "initrefnum": initrefnum,
        // "newrefnum": newrefnum
    }


    db.collection('users').insertOne(data, (err, collection) => {
        if (err) {
            throw err;
        }
        console.log("Record Inserted Successfully");
    });

    // return res.redirect('index.html')


})



app.get("/", (req, res) => {
    res.set({
        "Allow-access-Allow-Origin": '*'
    })
    return res.redirect('index1.html');
}).listen(3000);


console.log("Listening on PORT 3000");

mail.js


const nodemailer=require('nodemailer')

let mailTransporter = nodemailer.createTransport({
    service: 'gmail',
    auth: {
        user: 'entpsave@gmail.com',
        pass: '#Window123'
    }
});

let mailDetails = {
    from: 'xyz@gmail.com',
    to: 'samyakvermani@gmail.com',
    subject: 'Test mail',
    text: 'Node.js testing mail for GeeksforGeeks'
};

mailTransporter.sendMail(mailDetails, function(err, data) {
    if(err) {
        console.log('Error Occurs');
    } else {
        console.log('Email sent successfully');
    }
});

node.js – Role based authentication using Firebase and ReactJS

This is a advice seeking type post

I want to have two user types:

User
Admin
I’m going to user Firebase for authentication part only. Now let’s see what my users can do:

Register/login
Create post and make it public/private
Make a collection of post and make it public/private
And here’s what my admin can do:

Login
CRUD operation on users
View public/private posts and delete them
View public/private collection of posts and delete them
My question is can I do all of this using just Firebase and ReactJS? Or do I need a custom backend?

And what my rules for authenticaion for admin and user should look like if I just want a RBAC?

Is this enough?(found it in an article):

{
  "rules": {
    "users": {
      "$user": {
        ".write": "auth !== null && ((auth.token.isAdmin === true && data.child('isAdmin').val() === false) || auth.uid === $user)",
        ".read": "auth !== null && ((auth.token.isAdmin === true && data.child('isAdmin').val() === false) || auth.uid === $user)"
      },
      ".write": "auth !== null && auth.token.isAdmin === true",
      ".read": "auth !== null && auth.token.isAdmin === true"
    }
  }
}

javascript – Formatar campo de data para exibir na página EJS com Node.Js

Estou usando Node.JS para recuperar os dados de uma tabela de MySQL, porém eu gostaria que o campo de data fosse exibido na view EJS com o formato “DD/MM/YYYY”. Está sendo exibido “Thu Jul 15 2021 18:00:00 GMT-0300 (GMT-03:00)”

const Pedido = connection.define('pedido',{ 
   numero:{
       type: Sequelize.STRING(10),
       allowNull: true
   },
   dataemissao:{
       type: Sequelize.DATE,
       allowNull: true
   }
...

A view EJS está assim;

<% pedidos.forEach(pedido=>{%>                                                          
    <td><%=pedido.cliente.nome%></td>
    <td><%=pedido.dataemissao%></td>
<%});%>         

node.js – API request returning status code 404 not found

Im making a fantasy stock app. when making a valid request to the API, the data gets returned as expected. If a stock does not exist, the server returns “Request failed with status code 404”. I am trying to handle the error by logging the status to the console but the app does not catch the 404 error and the request stays pending. I cant find a way to handle the error so that it exits the promise to show the user that the stock is invalid.

my backend is as follows

app.get('/api/stocks', (req, res) => {
    const stockName = req.query.stockName
    axios({
        method: 'get',
        url: `https://sandbox.iexapis.com/stable/stock/${stockName}/quote?token=${testSecretKey}`
    })
        .then(response => {
            res.json(response.data);
        }).catch(err => {
        console.log(err.message)
    })
})

my front end

    handleSubmit = async e => {
        e.preventDefault();
        if (this.state.searchTerm !== '') {
            await axios.get("api/stocks", {
                params: {
                    stockName: this.state.searchTerm
                }
            })
                .then((res, req) => {
                    if (res.status === 200) {
                        this.setState({ stock: res.data, searchTerm: '', isStockValid: true });
                        console.log(res.status);
                    } else {
                        console.log(res.status)
                    }
                })
                // .catch(() => { console.log('error 404') });
            
            } else {
                alert('Enter a stock symbol. Example: AAPL for Apple inc.');
        }
    }

Erro ao instalar pacotes com npm Node.Js

Erro ao instalar pacotes com npm Node.Js – Stack Overflow em Português

node.js – Qual a melhor formar de trabalhar com autenticação de uma api Adonis.js 5 com um aplicativo?

Sempre utilizei o adonis v4 para minhas api’s, e como solução para autenticação utilizo tokens JWT com tokens de refresh.

Porem recentemente estudando a versão 5 do adonis percebi que não existem mais tokens JWT com refresh tokens, e pesquisando percebi como essa abordagem da v4 é insegura ou não recomendada.

Pois então me surgiu várias duvidas, já que na versão atual o conceito utilizado é opaque access token que entendi não pode ser lido a não ser pelo emissor, até ai tudo bem, mas como ele também possui a possibilidade de expiração para ser invalidado, como eu deveria abordar o fato de não conseguir realizar o refresh token automático?

  • Se eu tenho um app e defino este token para expirar em 1 hora, quando expirar, eu devo forçar o usuário realizar o login novamente?
  • Eu consigo realizar o refresh token com outra abordagem?
  • Devo deixar o token com um tempo de expiração maior?

DreamProxies - Cheapest USA Elite Private Proxies 100 Private Proxies 200 Private Proxies 400 Private Proxies 1000 Private Proxies 2000 Private Proxies 5000 Private Proxies ExtraProxies.com - Buy Cheap Private Proxies Buy 50 Private Proxies Buy 100 Private Proxies Buy 200 Private Proxies Buy 500 Private Proxies Buy 1000 Private Proxies Buy 2000 Private Proxies ProxiesLive.com Proxies-free.com New Proxy Lists Every Day Proxies123.com Buy Cheap Private Proxies; Best Quality USA Private Proxies