Home > other >  Nested promises receiving 301 error code and cors for second fetch
Nested promises receiving 301 error code and cors for second fetch

Time:11-04

I am attempting to create an API where you type in a player's name and you get the player position, team and then stats. The only thing is that while it uses the same public API, Ball Don't Lie, it requires two different fetches. So I am attempting to get the player id from the first promise and then feed it into the second. I get the first info and the id but when I attempt the second fetch I get this: Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://balldontlie.io/api/v1/stats?season[]=2020&player_ids[]=237. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing). Status code: 301.

Here is my code:

//The user will enter a NBA player, click on the type of stat, team, and receive their stats. Default will be all stats?

document.querySelector('button').addEventListener('click', apiRequest)

function apiRequest() {
    var player = document.querySelector('input').value;
    var season = document.querySelector('input[type="number"]').value;
    var id;
    
    fetch(`https://www.balldontlie.io/api/v1/players/?search=${player}`)
    .then(res => res.json()) //parse response as JSON
    .then(data => {
        object = data;
        id = object.data[0].id;
        
        document.querySelector('h2').innerText = `${data.data[0].first_name} ${data.data[0].last_name}`
        document.querySelector('.team').innerText = data.data[0].team['full_name']
        document.querySelector('.position').innerText = data.data[0].position

        
//nested fetches to send player id from one promise to another promise to get player stats 
    })
    .then (async data => {
        await new Promise(data => {
            return fetch (`https://balldontlie.io/api/v1/stats?season[]=${season}&player_ids[]=${id}`)
            .then(response => response.json())
            .then(data => {
                array[index] = {...e, ...data};
                console.log(data)
            })
        })
    })
    .catch(err => {
        console.log(`error ${err}`)
    })
}

I am using Node.js and Express so I am using CORS package. Below is my server.js.

const express = require('express');
const app = express();
const PORT = 8000;
const cors = require('cors');

app.use(cors());

//Body Parsing
app.use( express.json() );
app.use(express.urlencoded({    
    extended: true})); 
app.use(express.static("public"));

app.get('/', (req, res) => {
    res.sendFile(__dirname   '/index.html');
})

app.listen(PORT, () => {
    console.log(`The server is running on ${PORT}`);
})

CodePudding user response:

First off, your code is a bit confused for the second fetch() operation and in fact the promise created here in await new Promise(data => {...}). never resolves because you never call the first argument to the executor function (which you have inappropriately named data when it should be resolve).

Second, you don't have proper error handling on some of your promises so you may not be clearly seeing what errors are happening here.

So, first I'd suggest cleaning up the code and error handling and then rerun it to report exactly what you get:

//The user will enter a NBA player, click on the type of stat, team, and receive their stats. Default will be all stats?

document.querySelector('button').addEventListener('click', apiRequest)

function apiRequest() {
    const player = document.querySelector('input').value;
    const season = document.querySelector('input[type="number"]').value;

    console.log("about to run first fetch()");
    fetch(`https://www.balldontlie.io/api/v1/players/?search=${player}`)
        .then(res => res.json()) //parse response as JSON
        .then(data => {
            console.log("got first fetch() result");
            const object = data;
            const id = object.data[0].id;

            document.querySelector('h2').innerText = `${data.data[0].first_name} ${data.data[0].last_name}`;
            document.querySelector('.team').innerText = data.data[0].team['full_name'];
            document.querySelector('.position').innerText = data.data[0].position;


            //nested fetches to send player id from one promise to another promise to get player stats
            console.log("about to run second fetch()");
            return fetch(`https://balldontlie.io/api/v1/stats?season[]=${season}&player_ids[]=${id}`)
                .then(response => response.json())
                .then(data => {
                    console.log("got second fetch() result");
                    // not sure what array is here?  
                    // It isn't declared anywhere - shouldn't be doing this
                    array[index] = { ...e, ...data };
                    console.log(data)
                });

        }).catch(err => {
            console.log(`error ${err}`)
        });
}

And, I've added a little more logging about which fetch() operation is running so if you see an error displayed, you can see which fetch() operation caused it.

  • Related