简体   繁体   中英

I am trying to get data from my sql database to my react page, but my api returns an empty array

http://chucklets.no/getOnlineTime

When I click this I can see the JSON and it looks fine. But when using fetch it

API Node.js code:

app.get('/getOnlineTime', (req, res) => {
console.log("Reading rows from the Table...");
const arr = [];
connection.execSql(new Request('SELECT * FROM OnlineTime', function (err, rowCount, rows) {
    if (err) {
        console.error(err);
    }
})
    .on('doneInProc', function (rowCount, more, rows) {
        var row = {};
        for (let i = 0; i < rows.length; i++) {
            var row = {};
            for (let j = 0; j < rows[i].length; j++) {
                row[rows[i][j].metadata.colName] = rows[i][j].value;
            }
            arr.push(row);
        }
        res.json(arr)
    })
);
});

React code:

const [playerD, setPlayerData] = useState([]);
useEffect(() => {
    const fetchData = async () => {
        const response = await fetch('http://chucklets.no/getOnlineTime', {method:'GET'})
        if (!response.ok) {
            throw new Error(response.status);
        }
        const data = await response.text()
        setPlayerData(data)
    }
    fetchData()
}, [])

When using fetch on https://nba-players.herokuapp.com/players-stats I get a nice JSON. Any input would be greatly appreciated.

Because it works when you open the link in the browser and doesn't work per JS fetch, I suspect there might be some CORS issues and the Node.js isn't even responding. That's why I suspect the default value of the playerD variable in react is never updated and stay an empty array.

Try using the cors middleware: Express CORS Middleware

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM