0

I'm currently developing an application which uses a Node.js REST back-end with React.js on the client side.

I'm having issues when trying to make multiple fetch requests to my API, leading to stalled requests, which can take up to 2 minutes or more before the data returns.... I'm having no issues making single requests to the back-end in React or with Postman.

I have an endpoint in my back-end "/movies/{category}", which returns a list of movies depending on the chosen category. For example

/movies/horror
/movies/thriller
/movies/comedy

In my React app, the component structure is as follows:

APP
-- DASHBOARD
-- -- MOVIELIST (horror)
-- -- MOVIELIST (thriller)
-- -- MOVIELIST (comedy)

And in each of my MOVIELIST components, I'm doing a fetch to /movies/{category} in order to get the data.

If I just load a single MOVIELIST component, I have no issues. But as soon as I try to load more than one, the requests start stalling.

I've tried this in Chrome, FireFox, and IE, and the issue happens on all three.

Here is an example of the stalled request in Chrome:

enter image description here

Any help would be appreciated.

-

Update:

Here's how my back-end is set up

// index.js
const express = require('express');
const router = express.Router();

const app = express();    

const movies = require('./routes/movies');

app.use(express.json());
app.use('/api/movies', movies);

const port = process.env.PORT || 5000;    
app.listen(port, () => console.log(`Listening on port ${port}...`));

And then my endpoint for movies

//movies.js
const express = require('express');
const router = express.Router();
const moment = require('moment');
const sql = require('mssql');
const _ = require('lodash');

const config = require('../config/config');

//For CORS
router.options('/*', (req, res) => {
    res.header('Access-Control-Allow-Origin', "*");
    res.header('Access-Control-Allow-Methods', "GET, POST, PUT");
    res.header('Access-Control-Allow-Headers', ['Content-Type', 'x-access-token']).send();
});

router.get('/horror', auth, (req, res) => {
sql.connect(config).then(pool => {
        return pool.request().query(
            `SELECT STATEMENT`
        );
    }).then(result => {    
        sql.close();
        res.header('Access-Control-Allow-Origin', "*");
        res.header('Access-Control-Allow-Methods', "GET, POST, PUT");
        res.header('Access-Control-Allow-Headers', ['Content-Type', 'x-access-token']);
        return res.send(result);    
    }).catch(err => {
        sql.close();
        res.header('Access-Control-Allow-Origin', "*");
        res.header('Access-Control-Allow-Methods', "GET, POST, PUT");
        res.header('Access-Control-Allow-Headers', ['Content-Type', 'x-access-token']); 
        return res.send(err);
    });
})

router.get('/thriller', auth, (req, res) => {
    sql.connect(config).then(pool => {
            return pool.request().query(
                `SELECT STATEMENT`
            );
        }).then(result => {           
            sql.close();
            res.header('Access-Control-Allow-Origin', "*");
            res.header('Access-Control-Allow-Methods', "GET, POST, PUT");
            res.header('Access-Control-Allow-Headers', ['Content-Type', 'x-access-token']);
            return res.send(result);        
        }).catch(err => {
            sql.close();
            res.header('Access-Control-Allow-Origin', "*");
            res.header('Access-Control-Allow-Methods', "GET, POST, PUT");
            res.header('Access-Control-Allow-Headers', ['Content-Type', 'x-access-token']); 
            return res.send(err);
        });
    })

router.get('/comedy', auth, (req, res) => {
    sql.connect(config).then(pool => {
            return pool.request().query(
                `SELECT STATEMENT`
            );
        }).then(result => {        
            sql.close();
            res.header('Access-Control-Allow-Origin', "*");
            res.header('Access-Control-Allow-Methods', "GET, POST, PUT");
            res.header('Access-Control-Allow-Headers', ['Content-Type', 'x-access-token']);
            return res.send(result);        
        }).catch(err => {
            sql.close();
            res.header('Access-Control-Allow-Origin', "*");
            res.header('Access-Control-Allow-Methods', "GET, POST, PUT");
            res.header('Access-Control-Allow-Headers', ['Content-Type', 'x-access-token']); 
            return res.send(err);
        });
    })

module.exports = router;
2
  • 2
    It's a design/architecture issue (most likely on the back end...) Not an easy answer... If you have the code on github upload the link here and I'll try and help you... Commented Mar 19, 2019 at 19:53
  • Hey, I've edited my question with what my back-end code looks like. Commented Mar 19, 2019 at 20:10

2 Answers 2

1

I'm new in development, so you might take what I say not very seriously.

I'm thinking you're doing a bit too much when fetching data. You could fetch all movies in the dashboard, but make sure all movies have categories, then use a single endpoint to fetch movies based on categories passing in the category name as the query.

In the dashboard, have a getAllMovies endpoint -/movies/getAllMovies- that fetches all movies when the Home/Dashboard component renders.

Have three links/buttons for each of the category in the sidebar/navigation. Create a single endpoint - /movies/categories/${category_name}, for each category that you're interested in, pass in the category name as the query to the endpoint and fetch.

Like @SakoBu said put it on github and share the link.

Edit: There's an npm package for cors you can use, it will save you tons of keystrokes and make your code more readable.

https://github.com/expressjs/cors

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

1 Comment

Hey, the reason I didn't go with a getAllMovies is because the queries for the individual categories are actually slightly more complicated than just getting the category, and I didn't want to have to make super specific endpoints just to display certain things on the dashboard. Thanks for the NPM cors package though, that'll definitely make things cleaner!
0

This issue was fixed by using async/await on the backend.

router.get('/thriller', auth, (req, res) => {

     await getThrillers().then(result => {
        res.send(result);
    }).catch(err => {
        console.log(err)
    });

})

async function getThrillers(){   

    let promise = new sql.ConnectionPool(config).connect().then(pool => {
        return pool.request().query(`SELECT STATEMENT`)
    }).catch(error => {
        return error
    });

    let result = await promise;        

    return result;

}

Comments

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.