Heroku + Netlify gives - CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource

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 = "*"

image

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

Hey @malpick

The netlify.toml file needs to exist at the root of the repository, not in the src directory. Can you move it and see if that fixes the issue.

I tried moving it out from src to root and depolyed again but it didn’t seem to help. The same issue still persist.

The CORS error is being returned by Heroku, not Netlify. So adding headers to Netlify would not help.

You need proxy rewrites:

This error typically occurs in web development when making cross-origin requests. This error is related to the same-origin policy implemented by web browsers for security reasons. The same-origin policy restricts web pages from making requests to a different domain unless the server explicitly allows it by including the ‘Access-Control-Allow-Origin’ header in the response. To resolve this issue, the server hosting the requested resource needs to include the appropriate ‘Access-Control-Allow-Origin’ header, specifying the domain or origins allowed to access the resource. This can be done by configuring the server’s response headers or by using server-side middleware or frameworks that handle cross-origin requests.

JSON with Padding is just a way to circumvent same-origin policy, when CORS is not an option. This is risky and a bad practice. Avoid using this.

If you want to bypass that restriction when fetching the contents with fetch API or XMLHttpRequest in javascript, you can use a proxy server so that it sets the header Access-Control-Allow-Origin to *.

If you need to enable CORS on the server in case of localhost, you need to have the following on request header.

Access-Control-Allow-Origin: http://localhost:9999