by

Where communities thrive


  • Join over 1.5M+ people
  • Join over 100K+ communities
  • Free without limits
  • Create your own community
People
Repo info
Activity
    Caleb David
    @microworlds
    Hello guys, I have been getting a mongoose error "Can't save() doc multiple times". I posted the question on stackoverflow. Any assistance would be appreciated, thank you. Here's the link: https://stackoverflow.com/questions/61607900/updating-a-user-concurrently-in-mongoose-using-model-save-throws-error
    anD
    @and
    @microworlds, can you save the likes count in a variable and apply save at the end of the function? Which makes it one .save() instead of two?
    How can I view all available variables that are passed to a view?
    anD
    @and

    I encountered a strange issue and solved it eventually.

    My Person controller has add, create, edit and update function.
    After adding a Person, if I try creating one more person, the form will be autofilled. But if I restart the server, the form becomes empty. It was as if I was passing the 'person' object to the function.

    Eventually, I figured out that, my create function had a line like this:
    person = await Person.save();

    When I changed the line to:
    const person = await Person.save();
    the issue got resolved.
    So, my understanding is that Express keeps all the variables in one global scope.
    I wanted to know if there is a way to view all available variables in any give view.
    hillct
    @hillct
    Good evening all. I have a use case where I need to (at express server startup) run a request handler with a fully middleware populated request object, that specicially avoids having to call the public route. Can anyone advise how to instanciate a populated request object for use with Router.handle() as touched on here https://stackoverflow.com/a/33130094/1052093 ?
    General-Augustus
    @General-Augustus

    Hello,

    • I use windows and visualstudio with an express.js build.
    • I have setup a postgres data base with docker and pg admin, and i can connect with my credentials directly on docker (to test the connexion):
    
    bash-5.0# psql -U postgres -W users -p 5432 -h 172.17.0.2
    Password:
    psql (12.2)
    Type "help" for help.
    
    users=#

    Unfortunatly, when I put the credentials using pg (package for postgres) in app.js on my express.js app, i can't connect to the database. I tried many synthax but i can't figure where is the problem coming from (especially because the same credentials work perfectly on docker).

    
    const { Client } = require('pg')
    const client = new Client({
        user: 'postgres',
        password: '230933',
        host: '172.17.0.2',
        port: '5432',
        database:'users'
    })
    
    client.connect()
        .then(() => console.log("Connexion success to pg users database"))
        .catch(e => console.log("Failed to connect to pg users databse"))
        .finally(() => client.end())

    So, I still have my message"Failed to connect to pg users databse" in my console.

    General-Augustus
    @General-Augustus
    I found an ETIMEDOUT error, but i don't know how to fix it
    
    Error: connect ETIMEDOUT 172.17.0.2:5432
        at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1141:16) {
      errno: 'ETIMEDOUT',
      code: 'ETIMEDOUT',
      syscall: 'connect',
      address: '172.17.0.2',
      port: 5432
    } undefined
    anD
    @and
    Instead of IP, could you try the following implementation?
    https://codewithhugo.com/node-postgres-express-docker-compose/
    matrixbot
    @matrixbot
    sqz Also try to print the 'e' variable in your .catch()-block in console.log.
    sqz Otherwise it's very hard to figure out what's postgres is trying to tell you.
    General-Augustus
    @General-Augustus

    Thanks for the ideas, I am trying these things for 2 days.

    @and
    I am trying to understand how docker desktop work (I am new in programming), and before a full integration of posgresql in my app (like in the tutorial you show), i think it would be better that I understand how to simply run a postgresql container with docker desktop and try to connect on it from my windows machine. But i cant connect succesfully right now, i try to understand whats wrong in my dockerfile and my way to try to connect for 2 days :).

    @matrixbot
    As I said I am new, and i try dont understand what .catch()-block means yet :), but i am searching hard xD

    Indeed, thanks for these advices, it gives me new key where to look for

    Thiago Silva
    @Thiag0_Silv_twitter
    @General-Augustus are you running postgres in one container and express in another container and trying to connect between them?
    General-Augustus
    @General-Augustus

    @Thiago Silva
    The first time i used docker on windows (not docker destrop) and i successfully connected with my browser (with pg admin), but not with express js

    And now i am trying with docker desktop , and i try to connect from pgadmin before to test with the express app

    Thiago Silva
    @Thiag0_Silv_twitter
    Have you tried connecting using localhost instead of the docker IP?
    General-Augustus
    @General-Augustus

    @Thiago Silva I think it was that I should have done before...

    But now my dockerquickstart don't work anymore on my computer (since I installed docker desktop). And I had dome difficulties to make it runs .

    So i try to work on docker desktop with visual studio code. Maybe its better for the following to work on docker desktrop.

    If I build a docker image from a dockerfile following that tutorial :
    https://docs.docker.com/engine/examples/postgresql_service/

    Would I be able :

    • first, to connect independently from my browser
    • then, from the express app on my desktop ?
    Thiago Silva
    @Thiag0_Silv_twitter
    Do you have docker-compose installed @General-Augustus ?
    General-Augustus
    @General-Augustus

    @Thiago Silva
    Yes I think so because Docker compose is included on docker desktop on windows :

    Docker Compose relies on Docker Engine for any meaningful work, so make sure you have Docker Engine installed either locally or remote, depending on your setup.
    On desktop systems like Docker Desktop for Mac and Windows, Docker Compose is included as part of those desktop installs."

    General-Augustus
    @General-Augustus

    If I build an image with Docker desktop FROM ubuntu (dockerfile) with postgres.

    Would I be able to connect locally with my windows browser ? (with pg admin for windows and address localhost:5432) ?
    Or would the ubuntu image is considered as outside my "local system" ?

    1 reply
    hothdung
    @hothdung

    Dear community,

    I want to record audio every 15 seconds with the apple smart watch (Code for Iphone should look pretty much the same) and everytime send these audio recordings to the express API. The messages in console log got printed but the data body is empty.

    I hope you can help me out.

    Here is the express code

    https://easyupload.io/js2kjw

    Especially this part deals with receiving the audio file:

    app.post('/addAudio', function (req, res) {

    console.log("Audio is successfully posted!")

    console.log("Obtained audio data: ", req.body);

    })

    Here is the client code (Apple smartwatch/Iphone):

    https://easyupload.io/6rq8w1

    I hope you can help me out.

    Actually I wanted to just build a small client server app.

    Thank you very much.

    2 replies
    General-Augustus
    @General-Augustus

    I think I understand what the dockerfile could be useful for . It offers me the possibility to copy my app folder inside the container to run my app.

    FROM node:10
    
    WORKDIR /app
    
    COPY ./package.json .
    COPY ./package-lock.json .
    
    RUN npm install
    
    COPY . .
    
    EXPOSE 3000
    
    CMD npm start

    In you previous code, is there a way to rename the server adress : postgres to localhost ?

    anD
    @and
    @General-Augustus please check this article:
    https://codewithhugo.com/node-postgres-express-docker-compose/
    romie
    @theromie
    I am using express-routes-map and after running jest test i am getting TypeError: handler is not a constructor
    f0x52
    @f0x52
    I'm trying to catch errors that express should be throwing (EADDRINUSE: address already in use), but instead it just crashes. Here's the Unhandled 'error' event stacktrace and code to reproduce: https://gist.github.com/f0x52/84806bf2421380a42928b263ff92f02f
    Im starting to think this is a bug in Express?
    Jared Blumer
    @jaredblumer
    Hi I'm a junior developer interested in contributing to Express. Does anyone have any recommendations on how to learn and understand the code base? I've never contributed to an open source project before and would love to contribute to Express in any way I can.
    5 replies
    smile0811
    @smile0811
    express 如何实现邮件的收发,不用nodemailer模块,有没有 demo??
    Yves Kipondo
    @yvesdaxmaz
    @jaredblumer if you want to contribute the first step is to try to understand how request flow through request code till when the response is handling if you catch that working flow correct. Continue by trying to understand any bits of code inside express GitHub repository how few days just reading express codes, Things will appear more
    Yves Kipondo
    @yvesdaxmaz
    clear and after that go on https://github.com/expressjs/express/issues try to find some issue and reproduce them after what fine one which sound more simple for you and try to solve it,
    Jared Blumer
    @jaredblumer
    Thanks, @yvesdaxmaz. I'll give that a shot.
    Ivan Jeremic
    @ivanjeremic
    500k downloads for Koa and 13+million for express, why is express still so popular?
    Dev0n1in
    @devonlin
    Some people only know express
    Jared Blumer
    @jaredblumer

    In application.js why is exports included in addition to module.exports in
    var app = exports = module.exports = {};

    What function does exports serve?

    hothdung
    @hothdung

    I want to send different kinds of data (heartrate value, location, movement data, and audio data) to the server and put them into the database. The sending and inserting parts for heartrate, location, and movement work, but not for the audio data.

    In terms of the audio data, I want to send the audio file to the server transcribe that audio file into text and insert that text into the database. I have tested this part on its own and it worked. But when when the audio file is sent with the other data, a bunch of "trues" just pop up and I do not receive the transcription (done by a python script (worked)) of the audio files and nothing is stored into the database. Somehow, it feels like it gets blocked. But, I do not really know what is wrong with it? I tried to search, but could not find anything to it.

    Here is the app.js code

    var express = require('express');
    require('dotenv').config();
    var cors = require('cors');
    var mysql = require('mysql');
    var bodyParser = require('body-parser');
    var http = require('http');
    var app = express();
    var multer = require('multer');
    const path = require('path');
    const fs = require('fs')
    //var upload = multer({ dest: 'uploads/', limits: { fieldSize: 10000000000 } }).any()

    // building storage engine cb --> callback
    app.use(bodyParser.urlencoded({ extended: false }));
    app.use(bodyParser.json());
    app.use(bodyParser.raw({ type: 'audio/wav', limit: '60mb' }))
    app.use(cors());

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

    const storage = multer.diskStorage({
    destination: './public/uploads/',
    filename: function (req, file, cb) {
    cb(null, file.fieldname + '-' + Date.now() + path.extname(file.originalname));
    }
    });

    // Init upload
    const upload = multer({
    storage: storage,
    limits: { fileSize: 100000000 },
    fileFilter: function (req, file, cb) {
    checkFileType(file, cb);
    }
    }).single('studentAudio');

    // checking the extension and mimeType
    function checkFileType(file, cb) {

    const fileTypes = /wav/;
    // checking extension
    const extensionName = fileTypes.test(path.extname(file.originalname).toLowerCase());
    // checking mimeType
    
    console.log(file.mimetype === "audio/wav" && extensionName);
    
    if (file.mimetype === "audio/wav" && extensionName) {
        return cb(null, true);
    } else {
        cb('Just audio files allowed!!')
    }

    }

    function parseMovementData(movStr) {
    var result = movStr.split(" ");
    var values = [];
    var i;
    for (i = 0; i < result.length; i++) {
    var numStr = result[i].slice(result[i].lastIndexOf(':') + 1);
    var numVal = parseFloat(numStr);
    values.push(numVal);
    }

    return values;

    }

    // var jsonObj = convertToText(req.file.path, req.filename, req.body.date);
    //"../data/test.csv"
    //convertToText("public/uploads/test2.wav", "AudioText6test", "2020-05-11 16:04:22");
    // function convertToText(audioPath, filename, date) {
    // const spawn = require('child_process').spawn;
    // const scriptExecution = spawn("python", ["audioTranscribe.py"])
    // var info = [audioPath, date];
    // var text;
    // scriptExecution.stdout.on('data', function (data) {
    // var text = data.toString()
    // console.log("Here: " + data.toString());
    // // saving transcribed files into transcriptions folder
    // fs.writeFile('./transcriptions/' + filename + '.txt', text, function (err) {
    // if (err) {
    // return console.log(err)
    // }
    // console.log("File created!")
    // })

    // });
    // scriptExecution.stdin.write(JSON.stringify(info));
    // scriptExecution.stdin.end();
    // }

    // connection to interventions_db

    var connection = mysql.createConnection({
    host: process.env.DB_HOST,
    user: process.env.DB_USER,
    password: process.env.DB_PASS,
    database: process.env.DB_DATABASE,
    port: process.env.DB_PORT
    })

    var signalsConnection = mysql.createConnection({
    host: process.env.DB_SIG_HOST,
    user: process.env.DB_SIG_USER,
    password: process.env.DB_SIG_PASS,
    database: process.env.DB_SIG_DATABASE,
    port: process.env.DB_SIG_PORT
    })

    var outputConnection = mysql.createConnection({
    host: process.env.DB_OUT_HOST,
    user: process.env.DB_OUT_USER,
    password: process.env.DB_OUT_PASS,
    database: process.env.DB_OUT_DATABASE,
    port: process.env.DB_OUT_PORT
    })

    app.post('/interventions', function (req, res) {
    const intervention = {
    interventionType: req.body.interventionType,
    place: req.body.place,
    students: req.body.students,
    date: req.body.date,
    time: req.body.time,
    severity: req.body.severity,
    teachers: req.body.teachers
    }

    var q = "INSERT INTO interventions SET ?;";
    
    connection.query(q, intervention, function (error, result) {
        if (error) throw error;
        console.log(result);
        res.send("Posted to DB");
    })
    console.log
    Lachie-Source
    @Lachie-Source
    Hello! I'm using firebase for my project's database. Im just wondering how I can serve a static file in my database (I know that probably doesn't make sense). Here's what I mean:
    app.use('/data', express.static("https://imigy-d2ea7.firebaseio.com/"))
    Hugo Miranda
    @hugoanalistaweb
    hi
    image.png
    Help!
    doppelgunner
    @doppelgunner

    hi any idea how to solve this issue:

    the client times out because the express server it is talking to is taking too long to process the request. causing it to retry automatically. what I need is to stop the retry and set timeout to forever so it will wait for forever. any idea how?

    doppelgunner
    @doppelgunner
    reference to the lib im using: https://visionmedia.github.io/superagent/
    go to timeout section
    Julio Sepia
    @jsepia
    Hi. Is there a way to call an Express router or app from within a request handler? Like this?
    import router1 from './router1'
    import router2 from './router2'
    
    app.use(function (req, res, next) {
      if (condition) {
        router1.handleRequest(req, res, next)
      }
      else {
        router2.handleRequest(req, res, next)
      }
    })
    Mazen Elkashef
    @lkashef
    Hey @jsepia, middlewares are like a chain, you could chain middlewares, and execute it's handler based on your condition.
    app.use(function (req, res, next) {
        if (condition) {
          router1.handleRequest(req, res, next)
        }
    });
    app.use(function (req, res, next) {
        if (!condition) {
          router1.handleRequest(req, res, next)
        }
    });
    You could share the case use, maybe we could recommend something better
    Julio Sepia
    @jsepia
    That works too, but what I ultimately want is this "handleRequest" method. I used handleRequest as a placeholder in my example, but it's not a real method of Router. I looked through the TypeScript typings and I couldn't find a Router method that can be called as a request handler. I guess what I'm looking for is a workaround that allows me to route a request from a request handler dynamically, without having to write my own router implementation.
    Julio Sepia
    @jsepia

    If it helps, here's my use case: I have an Express app with a single request handler that lives in its own file. And I'm using chokidar to hot-reload the request handler when I make changes to its code. I would like to replace this single request handler with a router. I renamed the fictional handleRequest method to make it clearer that it's a placeholder. Here's a simplified example:

    app.ts

    import express from 'express'
    import chokidar from 'chokidar'
    
    const app = express()
    const watcher = chokidar.watch('./src/server')
    
    watcher
      .on('ready', function() {
        watcher.on('all', function() {
          console.log('Clearing module cache from server')
          Object.keys(require.cache).forEach(function(id) {
            if (/src[\/\\]server[\/\\]/.test(id)) {
              delete require.cache[id]
            }
          })
        })
      })
    
    app.use(function (req, res, next) {
      const handler = require('./src/server').default
      handler(req, res, next)
    })
    
    app.listen(3000)

    src/server/index.ts

    import { RequestHandler } from "express"
    import router from './router'
    import { createUserHandler, getUserHandler, updateUserHandler } from './users
    
    console.log(Object.keys(router))
    
    const handler: RequestHandler = (req, res, next) => {
      // right now I'm doing my own routing
      if (req.method === 'POST') {
        if (req.path.match(/^\/users\/new$/)) {
          createUserHandler(req, res, next)
        }
        else if (req.path.match(/^\/users\/[0-9]+$/)) {
          updateUserHandler(req, res, next)
        }
      }
      else if (req.method === 'GET' && req.path.match(/^\/users\/[0-9]+$/)) {
        getUserHandler(req, res, next)
      }
    
      // what I actually want is to
      // leave the routing to a router
      // router.HANDLE_THE_REQUEST(req, res, next)
    }
    
    export default handler
    I'm aware the traditional way to use routers is to add them to the chain with app.use(), but this would preclude me from hot-reloading the router (unless there's a way to unmount middleware)