0

I'm new to javascript and nodejs and i have a question

I have a code who i'm working in a simple api and i'm getting a lot of trouble to understand why this is happening

app.get('/api/list_all', (req, res) => {
    get_info(`SELECT * FROM users;`, function(result){
        res.json(result);
    });
});

I have this route to list all the users for me on screen for a local host mysql. The connection are working but when i type the route, returns me a blank screen with "[]" (empty list)

The console and the html page does not display any errors

But when i change the route for just "list_all" without the "api" part, it goes well. Like this:

app.get('/list_all', (req, res) => {
    get_info(`SELECT * FROM users;`, function(result){
        res.json(result);
    });
});

It returns me with the SQL response.

The question is: why is not working when i give the "api" on route?

The function "get_info":

function get_info(sql_data, callback){

    con.getConnection((error, conn) => {
        if (error) { throw error; }
        conn.query(
            sql_data,
            (error, resultado) => {
                conn.release();
                if (error) { throw error; }
                return callback(resultado)
            }
        )
    })
}

I was expecting the route "api/list_all" to return the SQL result with all users normally.

1 Answer 1

0

You are probably importing wrong your code to your main server file

If the code shown above is in a different file from your server file you should add in the server.js the line app.use('/api/list_all',imported_route); and then change your code to

    app.get('/', (req, res) => {
    get_info(`SELECT * FROM users;`, function(result){
        res.json(result);
    });
   });

For more help refer to previous question routing not working in node.js and express.js API

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

1 Comment

Soo, i was doing all in the same "main.js" script for a test but i saw the answer of the refer who you attached in and solved here the problem. Correct if i'm not mistaken but i have to create a new line of routes to get an adicional route like i have to create an "api" route to create the path "api/list_all". That's right? Thank you for our help, i'm new at nodejs.

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.