I am using Express.JS (backend) and React.js (front end) for my app on Heroku. The following Node.js code works when I am running my app locally,
//code based off of:
// https://medium.com/@dtkatz/3-ways-to-fix-the-cors-error-and-how-access-control-allow-origin-works-d97d55946d9
const express = require('express');
const request = require('request');
const app = express();
const apiKey = 'API-key';
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', '*');
next();
});
app.get('/getCoinInfo', (req, res) => {
console.log('The request has been received!!')
request(
{ url: 'https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest?CMC_PRO_API_KEY=' + apiKey},
(error, response, body) => {
if (error || response.statusCode !== 200) {
return res.status(500).json({ type: 'error', message: err.message });
}
res.json(JSON.parse(body));
}
)
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => console.log(`listening on ${PORT}`));
But it does not work when I am deploying my app on heroku. When I console.log my response on the heroku version I get this
Where the "type" of request is "basic" instead of "cors" . My local version runs fine and a console.log of the response looks like this:
The only difference between my local version of my code and the Heroku version is that I am sending my request to a different address (my heroku app address instead of localhost3000)
const getData = async () => {
let data = ''
try {
const req =
`https://cryptoreactv2.herokuapp.com/getCoinInfo`;
const response = await fetch(req);
console.log(response)
console.log(response.json())
data = await response.json()
await console.log(data);
await setApiData(data);
await searchData(query);
} catch(e) {
console.log('Request could not be furfilled because of ' + e);
}
}