Search code examples
javascriptmysqlnode.jspostpostman

I can't view the information I sent with js in postman


With the code below, I can enter information in my MySQL table in the post method and the information is recorded in the table. I also check it in the js terminal. With the "node api.js" command, it appears that the last information is registered. but the last added info doesn't show up when I look with the postman.

const mysql = require('mysql');
const express = require('express');
const app = express();
const port = 3000;

let cevap;

const baglanti = mysql.createConnection({
    host: 'example',
    user: 'example',
    password: 'example',
    database: 'example'

});

baglanti.connect();

baglanti.query('SELECT * FROM users', function (error, results, fields) {
    if (error) throw error;

    cevap = results;
    console.log(results);
    baglanti.end();
});

app.post('/users', (req, res) => {
    res.send(cevap);
});

app.listen(port, () => {
    console.log("worked"); 
});

if you look at the first photo, I can see the information added in the terminal, but the last entered information is not visible in the second photo, that is, on the postman screen.

  1. Terminal image
  2. Postman image

What I want is to be able to view all added users in postman. When I add a new user, see it instantly from postman (already registering to MySQL table)


Solution

  • You HAVE TO query fresh data from the databse EVERY time you want your fresh data.

    Ofc. you could cache it or something but thats probably too advanced for this case.

    const mysql = require('mysql');
    const express = require('express');
    const app = express();
    const port = 3000;
    
    const sql = mysql.createConnection({
        host: 'example',
        user: 'example',
        password: 'example',
        database: 'example',
    });
    
    sql.connect();
    
    app.post('/users', (req, res, _next) => {
        sql.query('SELECT * FROM users', function (error, results, fields) {
            if (error) throw error;
    
            console.log(results);
            res.send(results);
        });
    });
    
    app.listen(port, () => {
        console.log(`Server running at http://localhost:${port}`)
    });