Hi there,
I’m having issues with deploying an application that uses heroku for server/backend (node js (express)) and netlify for client (React).
Seems like I’m running into this error when trying to make use of api calls between heroku and netlify.
Access to XMLHttpRequest at ‘https://avanzbase.herokuapp.com/popular-stock?symbol=DIS’ from origin ‘https://upbeat-northcutt-4650a4.netlify.app’ has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.
I have looked through a lot of questions regarding this but can’t figure out how to solve it. As I understand you are suppose to have a file - netlify.toml in root directory in client to handle redirects and headers, which I have added like so:
# The following redirect is intended for use with most SPAs that handle
# routing internally.
[[redirects]]
from = "/*"
to = "/index.html"
status = 200
[[headers]]
# Define which paths this specific [[headers]] block will cover.
for = "/*"
[headers.values]
Access-Control-Allow-Origin = "*"
However, this has not helped. I also understand that sometimes it may be necessary to create a proxy? But if possible I would prefer not having to do this step.
Moving on to what the code looks like at the moment.
This is what the server side looks like at the moment (including “/popular-stock” at the end to give you an idea of how it looks):
const express = require("express");
const app = express();
require("dotenv").config();
const cors = require("cors");
const mysql = require("mysql");
const jwt = require("jsonwebtoken");
const cookieParser = require("cookie-parser");
// port for heroku if needed
const PORT = 3001;
// app objects instantiated on creation of the express server
app.use(
cors({
origin: ["https://upbeat-northcutt-4650a4.netlify.app"],
methods: ["GET", "POST", "DELETE"],
credentials: true,
origin: true,
})
);
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(cookieParser());
app.get("/popular-stock", async (req, res) => {
try {
const response = await axios.get(
`https://finnhub.io/api/v1/quote?symbol=${req.query.symbol}&token=${process.env.REACT_APP_API__KEY_FINNHUB}`
);
res.json(response.data);
} catch (e) {
console.log(`Axios request failed: ${e}`);
}
});
app.listen(process.env.PORT || PORT, () => {
console.log(`Server running on port ${PORT}`);
});
And for the client side it looks like this:
import axios from "axios";
export const GetPopularStockData = (symbol) => {
try {
const response = axios
.get(`https://avanzbase.herokuapp.com/popular-stock?symbol=${symbol}`, {})
.catch(function (err) {
if (err.response) {
return err.response;
}
});
return response;
} catch (e) {
console.log(`Axios request failed: ${e}`);
return null;
}
};
Site name: https://upbeat-northcutt-4650a4.netlify.app