2

I'm trying to get some data from a mysql database.

The backend seems to work fine, the data is being logged there but not in the frontend.

app.post('/api/user/database_test', (req, res, next) => {

  var result;

  database.query('SELECT * FROM test', function (error, response, fields) {
    if (error) throw error; 
    console.log('response:', response);

     result = response; 
     console.log('result: ', result) //works fine
  })

  res.status(200).json({
    message: 'Data from Database :',
    result: result
  })
});

This is displayed in the backend console:

result:  [
  RowDataPacket {
    userid: '1',
    username: 'testuser',
    firstname: 'testname',
    lasname: 'testname2',
    email: '[email protected]',
  }
]

But i also need to display the data i the frontend so i tried it like this.

 async getFromDB() {

    var obj = 'test';

    this.http.post('http://localhost:3000/api/user/database_test', obj)
      .subscribe((response) => {
        
        console.log('response: ', response)  


      })
  }  

But i only receive the message 'Data from database' in the browser console but no actual data. I also tried to log response.result but the code does not compile anymore.

What am I doing wrong?

2
  • Open the devtools and look into network tab to see the request. Maybe something is wrong. Paste the image if you can :) Commented Mar 13, 2023 at 13:23
  • Try taking the async off your method, returning the Observable in your service method, and subscribing to it in the component. Commented Mar 13, 2023 at 13:30

1 Answer 1

1

The problem is with the backend code: db.query is async, so res.json returns results before db part is done, so you return empty results to the client, before they're actually pulled.

Try moving the response part inside db.query, so that res.json runs when the db.query is done:

app.post('/api/user/database_test', (req, res, next) => {


    database.query('SELECT * FROM test', function(error, response, fields) {
        if (error) throw error;
        console.log('response:', response);

        console.log('result: ', response) //works fine

        res.status(200).json({
            message: 'Data from Database :',
            result: response
        });

    })


});
Sign up to request clarification or add additional context in comments.

1 Comment

This works perfectly. Thank you very much, i will upvote as soon as i have enough reputation :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.