Forum

You are not logged in.

#1 27-10-2017 15:52:00

jmpp
Membre
Registered: 27-10-2017
Posts: 4

Node app with MongoDB

Hello,

I tried to deploy my node and mongo application. It's a simple REST api which must deliver json content from the mongo database.

The server seems to be correctly running as I can see the process in the admin panel ...
process.png
... but when I try to reach the URL http://jmpp.alwaysdata.net/intranet-server , I get a 404 from Express :
Cannot GET /intranet-server

Here's my config :
config.png

My FTP tree :
ftp.png

And my `index.js` :

require('colors')

const path = require('path')
const express = require('express')
const mongoose = require('mongoose')
const bodyParser = require('body-parser')

// Config
const SERVER_IP   = process.env.ALWAYSDATA_HTTPD_IP || 'localhost'
const SERVER_PORT = process.env.ALWAYSDATA_HTTPD_PORT || 1337

const MONGO_DSN = 'mongodb://<MY_LOGIN>:<MY_PASSWORD>@mongodb-jmpp.alwaysdata.net/<MY_DB_NAME>'

// Création d'une application ExpressJS
const app = express()

const collaborateur = require('./Collaborateur.controller')

app.use(bodyParser.json())

// Middleware qui permet d'autoriser les requêtes Ajax provenant d'un autre domaine
app.use((req, res, next) => {
    res.header('Access-Control-Allow-Origin', '*')
    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE')
    res.header('Access-Control-Allow-Headers', 'Content-Type')
    next()
})

app.get('/collaborateurs', collaborateur.findAll)
app.get('/collaborateur/:id', collaborateur.find)
app.post('/collaborateur', collaborateur.create)
app.put('/collaborateur/:id', collaborateur.update)
app.delete('/collaborateur/:id', collaborateur.remove)

// Indique à Mongoose que les promesses à utiliser sont celles par défaut dans Node.js (objet global)
mongoose.Promise = global.Promise

// Connexion à la base de données MONGO
mongoose.connect(MONGO_DSN, { useMongoClient:true })
        .then( () => console.log(' MongoDB '.bgGreen , 'Connexion établie !'.green ),
               () => console.log(' MongoDB error '.bgRed , 'Auriez vous oublié de lancer `mongod ?`'.red ) )
        .then( () => app.listen(SERVER_PORT,
                                SERVER_IP,
                                () => console.log(' App Started '.bgGreen, 'Le serveur http://'+ SERVER_IP +':'+ SERVER_PORT +' est prêt !'.green)) )
        .catch(err => console.log(err.red))
        

As I get a 404 response from Express, I'm sure the server is running, but don't know what's wrong.

Is there any place where I can see the logs produced by the command node ~/intranet-server/index.js ? I tried to analyze the process, but nothing helpful here.

Last edited by jmpp (27-10-2017 15:54:04)

Offline

#2 27-10-2017 16:29:15

@Cyril
Staff
From: Paris
Registered: 06-02-2007
Posts: 5,587
Website

Re: Node app with MongoDB

Hello,

Your application is reachable at http://jmpp.alwaysdata.net/intranet-server, and when you go to that URL, the path (as received by your application) is '/intranet-server', not just '/'. I assume that's not what your application is expecting.

You should either modify your application to accept that path, or install your application at the root URL.

Offline

#3 27-10-2017 16:43:56

jmpp
Membre
Registered: 27-10-2017
Posts: 4

Re: Node app with MongoDB

Hello Cyril,

Thanks for your answer.

It make sense now you say it. I'll try edit my app index in a couple of minutes when I'll be home.

Just to be curious, is it possible to consult the process logs and crashes if it occur ? Or should I set up my own logging strategy with packages like "winston" ?

Thanks smile

Offline

#4 27-10-2017 16:46:01

@Cyril
Staff
From: Paris
Registered: 06-02-2007
Posts: 5,587
Website

Re: Node app with MongoDB

Not possible yet, but it will very soon (the feature has been developped and needs to be deployed in production).

Offline

#5 27-10-2017 17:45:51

jmpp
Membre
Registered: 27-10-2017
Posts: 4

Re: Node app with MongoDB

Okay.

I've updated my index.js and now it seems to respond to the main route.

This URL ...

http://jmpp.alwaysdata.net/intranet-ser … aborateurs

... reaches this line :

app.get('/intranet-server/collaborateurs', collaborateur.findAll)

and here's the 'findAll' method :

    exports.findAll = (req, res) => {
        // res.send('Test response !')
        Collaborateur.find({}).exec().then(collaborateurs => {
            if (collaborateurs === null) return res.json({message : 'Aucun utilisateur trouvé'})
            res.json(collaborateurs)
        }).catch(err => {
            res.json({ error : 1, message : err.message })
        })
    };

If I un-comment the second line, I get "Test response !" as response.

But as written above, the /intranet-server/collaborateurs route doesn't respond. It keep loading in the browser until having an ERR_EMPTY_RESPONSE

I've put catch statements everywhere, so I don't think it comes from my code. But as I can't see any logging information, I still don't understand what's happening wrong here.

Any though ?

[Edit]

For information (if it can helps), 'Collaborateur' is a Mongoose model as described here :

const mongoose = require('mongoose')

mongoose.Promise = global.Promise

// Création d'un Schéma qui définit la structure d'un document "collaborateur"
const collaborateurSchema = new mongoose.Schema({
    gender   : { type: String, required: true },
    firstname: { type: String, required: true },
    lastname : { type: String, required: true },
    email    : { type: String, required: true },
    phone    : { type: String, required: true },
    birthdate: { type: String, required: true },
    city     : { type: String, required: true },
    country  : { type: String, required: true },
    photo    : { type: String }
}, { collection : 'collaborateurs' })

// Fabrication d'un "Modèle" à partir de ce schéma de données
// Un modèle mongoose contient les méthodes permettant d'aller chercher/modifier/supprimer dans la base (.find() .sort() .count() .findOne(), insert(), insertMany() ... etc )
const collaborateurModel = mongoose.model('Collaborateur', collaborateurSchema)

module.exports = collaborateurModel

Of course, the "collaborateurs" collection exists in my alwaysdata database, and contains for now one document.

Last edited by jmpp (27-10-2017 17:49:27)

Offline

#6 30-10-2017 18:20:43

jmpp
Membre
Registered: 27-10-2017
Posts: 4

Re: Node app with MongoDB

Still no idea to solve my problem ?

Again I focused on it today, but still don't know what's going on and why the route keeps not responding sad

Everything is fine while running the app locally.

Last edited by jmpp (30-10-2017 18:21:11)

Offline

#7 31-10-2017 09:44:35

@Cyril
Staff
From: Paris
Registered: 06-02-2007
Posts: 5,587
Website

Re: Node app with MongoDB

This is clearly an issue with your application. You said it works fine locally; do you have the exact same Node.js version? Have you tried running your application on our SSH servers? Does it work?

Offline

Board footer

Powered by FluxBB