简体   繁体   中英

Internal Server Error while using heroku and bcryptjs

My friend and I are developing a frontend website where we need to encrypt some data before it goes to a database. We were advised to use bcryptjs and so we did

On the following code you can see our middleware:

const jwt = require('jsonwebtoken'); //módulo NPM
const config = require('./config.js'); //ficheiro de configuração

let checkToken = (req, res, next) => {
let token = req.headers['x-access-token'] || req.headers['authorization'];
if (token.startsWith('Bearer ')) {
    token = token.slice(7, token.length); //remove a palavra ‘Bearer ’
    }
    if (token) {
    jwt.verify(token, config.jwtSecret, (err, decoded) => {
    if (err) {
    return res.json({
    success: false,
    message: 'O token não é válido.'
    });
    } else {
    req.decoded = decoded;
    next();
    }
    });
    } else {
        return res.json({
            success: false,
            message: 'Token indisponível.'
            });
            }
            };
            module.exports = {
            checkToken: checkToken
            }

Router:

router.get('/list', middleware.checkToken,utilizadorController.list);

App.js:

app.use('/utilizador', middleware.checkToken,utilizadorRouters)

We think everything is connected correctly however when we run our site just appears a message saying "Internal Server Error", since we are using heroku we executed heroku logs --tail this command so we can have access to logs, we found out that the problem is on the terminal 2021-06-02T20:06:44.372296+00:00 app[web.1]: TypeError: Cannot read property 'startsWith' of undefined , this is related to the first if at the middleware code (posted above)

Why are we getting this error? And does it have any solution?

I guess this line

let token = req.headers['x-access-token'] || req.headers['authorization'];

finds no token in either header. So token comes back undefined, rather than a string. So token.startsWith() doesn't work and gives the error you saw.

When something like this gacks, the web server throws back a 500 error to the browser.

To troubleshoot: Do console.log(req.headers) and look at the output. It looks to me like the http request you send lacks either one of those headers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM