Home > OS >  Node Express Router does not respond, nor throwing errors. What did i do wrong?
Node Express Router does not respond, nor throwing errors. What did i do wrong?

Time:12-12

I hosted the server on a my laptop (ubuntu 22.04), and on docker (various nodejs versions). I don't get any errors, but i cant get a response either. I installed morgan which just emits

GET /test - - ms - -

I found out, that the server is not answering the request but i could not figure out why.

This is my code, i followed this tutorial. If you need more details, let me know.


index.js

// import modules
const express = require('express');
const cors = require('cors');
const logger = require('morgan');

// import local modules
const routes = require('./routes/router.js');

// define express app
const app = express();

// enviroment variables
const PORT = process.env.PORT || 3000;
const HOST = process.env.HOST || '0.0.0.0';

app.use(logger('dev'));

// use jsonParser
app.use(express.json);

// use cors, allow all
app.use(cors());


// serve static filesn 
// app.use('/', express.static('dist'))

// use router for requests
app.use(routes);

// start server on predefined port
app.listen(PORT, HOST, (err) => {
    if (err) {
        console.log(err);
    } else {
        console.log(`Running on http://${HOST}:${PORT}`)
    }
});

router.js


// import modules
const express = require('express');
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const uuid = require('uuid');

// import local modules
const db = require('../lib/db.js');
const userMiddleware = require('../middleware/users.js');

// constants
var router = express.Router();

// routes

// test route
router.get('/test', (req, res, next) =\> {
console.log(req);
res.status(200).send({ message: 'you did it!!!s' });
});

// Sign-Up Route
// http://localhost:3000/sign-up
router.post('/sign-up', userMiddleware.validateRegistration, (req, res) =\> {
console.log('sign-up');
db.query(`SELECT id FROM Accounts WHERE LOWER(username) =  LOWER(${req.body.username})`, (err, result) =\> {
// check if username is taken
if (result && result.length) {
return res.status(409).send({
message: 'username already exists'
});
} else {
bcrypt.hash(req.body.password, 10, (err, hash) =\> {
if (err) {
return res.status(500).send({
message: 'server error'
});
} else {
db.query(`INSERT INTO Accounts (id, username, passwordHash, registered) VALUES ('${uuid.v4()}', ${db.escape(req.body.username)}, '${hash}', now());`, (err, result) =\> {
if (err) {
return res.status(400).send({
message: err
});
}
return res.status(201).send({
message: 'user registered'
})
});
}
});
}
});
});

// Sign-In Route
// http://localhost:3000/sign-in
router.post('/sign-in', (req, res) =\> {
console.log('sign-in');
db.query(`SELECT * FROM Accounts WHERE username =(${db.escape(req.body.username)})`, (err, result) =\> {
if (err) {
return res.status(400).send({
message: err
});
}
if (!result.length) {
return res.status(401).send({
message: 'incorrect password or username'
});
}

        bcrypt.compare(req.body.password, result[0]['password'], (bErr, bResult) => {
            if (bErr) {
                return res.status(401).send({
                    message: 'incorrect password or username'
                });
            }
            if (bResult) {
                const token = jwt.sign(
                    {
                        username: result[0].username,
                        userId: result[0].id,
                        userRole: result[0].role
    
                    },
                    'superSecret#',
                    { expiresIn: '7d' }
                );
                db.query(`UPDATE Accounts SET last_login = now() WHERE id = ${result[0].id};`);
                return res.status(200).send({
                    message: 'logged in',
                    token,
                    user: result[0]
                });
            }
            return res.status(401).send({
                message: 'incorrect password or username'
            });
        });
    });

});

// http://localhost:3000/cocktails
router.get('/cocktails', (req, res) =\> {
console.log(req.url);
res.status(200).send({ message: 'you did it!' });
});

// export functions
module.exports = router;

db.js

// import modules
const mysql = require('mysql2');

const connection = mysql.createConnection({
    host: 'database',
    user: 'root',
    database: 'project01',
    password: '********'
});
connection.connect((err) => {
    if (err) {
        return console.log('Error: '   err.message)
    }
    return console.log('Established database connection');
});

// export functions
module.exports = { connection };

The only server console output is:

Running on http://0.0.0.0:3000
Established database connection
GET /test - - ms - -

CodePudding user response:

Change app.use(routes) as app.use("/",routes) for handling /test route

CodePudding user response:

A stupid typo causes this behaviour: I wrote

app.use(express.json);

instead of

app.use(express.json();

I hope this will help anybody

  • Related