Ad

Browser Tab Keeps Loading After Express Js Get Method

- 1 answer

I'm trying to build a simple REST API using Express.js, first time using it.

So I run the Express application generator using npx express-generator. Then, on /routes/users.js, I add a get method to retrieve data from an MSSQL database with the following code:

router.get('/api/v1/test', (req, res) => {
    (async () => {
        try {
            let pool = await sql.connect(dbConfig);
            let result1 = await pool.request().query('select * from andromedadb.dbo.test');
            console.dir(result1);
        } catch (err) {
            console.log('err', err);
        }
    })();
});

I know the connection is successful because the console prints the following:

{
  recordsets: [ [ [Object] ] ],
  recordset: [ { id: 1, name: 'hello', age: 17 } ],
  output: {},
  rowsAffected: [ 1 ]
}

My issue is that the browser tab keeps loading and executing the get method over and over.

I also tried the code snippet on https://www.js-tutorials.com/nodejs-tutorial/simple-example-of-nodejs-express-with-mssql/#Listing_Nodejs_MSSQL_Using_Express, but the very same thing was happening.

Thanks in advance.

Ad

Answer

You need to send back some response with your res object or call the next() function to go into your next middleware, otherwise you are just leaving your request hanging, thus the infinite load. Add a res.send() or res.json() function to mark the end of your function.

router.get('/api/v1/test', (req, res) => {
(async () => {
    try {
        let pool = await sql.connect(dbConfig);
        let result1 = await pool.request().query('select * from andromedadb.dbo.test');
        console.dir(result1);
res.status(200).send("Received the response successfully");
    } catch (err) {
        console.log('err', err);
res.status(500).send("Something went wrong");
    }
})();
});
Ad
source: stackoverflow.com
Ad