I cannot connect the Mysql Nodejs database

Asked

Viewed 237 times

-2

It should show the table data on the screen, but does not return anything. Where I am missing?

module.exports = function(app){

app.get('/noticias', function(req, res){

   var mysql = require('mysql');

   var connection = mysql.createConnection({
      host : 'localhost',
      user : 'root',
      password : '1234',
      database : 'portal_noticias'
   });

   connection.query('select * from noticias', function(error, result){
        res.send(result);
   });
   //res.render("noticias/noticias");
 });
};

1 answer

3

You are not checking for possible errors at any time. I suggest the following changes, so the errors will be shown and it will be easier to find the problem:

const mysql = require('mysql');
const { promisify } = require('util');

const listar = async () => {
  const conexao = mysql.createConnection({
    host : 'localhost',
    user : 'root',
    password : '1234',
    database : 'portal_noticias'
  });

  const query = promisify(conexao.query);

  return query('select * from noticias');
};

module.exports = (app) => {
  app.get('/noticias', async (req, res) => {
    try {
      res.send(await listar());
    } catch(e) {
      console.error(e);
      res.status(500).send(e.message);
    }
  });
};

Browser other questions tagged

You are not signed in. Login or sign up in order to post.