CORs and Netlify - API requests not working on deployment

Hi guys…

Having this awful CORs and Netlify issue we all been talking about :frowning:

My site is: https://competent-mayer-42a09b.netlify.app/

I want to implement a basic contact database from a form to collect some user info. My solution works well locally, but when I deploy my app, I get this error:

Access to XMLHttpRequest at 'https://ometer-back.herokuapp.com/' from origin 'https://competent-mayer-42a09b.netlify.app' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
POST https://ometer-back.herokuapp.com/ net::ERR_FAILED 503

I have followed advice from this forum thread and this one … with no luck. I now have in the root of my ReactJS project this Netlify.toml configuration:

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

I read about a headers file and a proxy that I might have to add?

But I have not done this before and it’s confusing to me, as I am just getting familiar with serving up the static build content of my React application.

On my React Axios post request I’ve included header info

 await axios.post(process.env.REACT_APP_API_ENDPOINT,
      {
        crossdomain: true
      }, 
      {
      headers: {
        'Access-Control-Allow-Origin' : '*',
        'Access-Control-Allow-Methods':'GET,PUT,POST,DELETE,PATCH,OPTIONS', 
        'Content-Type': 'application/x-www-form-urlencoded'      
      }
    },

On my server I’ve included…

app.use(cors({
    // origin: process.env.ORIGIN
    origin: "*",
    methods: ["GET", "POST"]
}));
app.use(function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*"); // update to match the domain you will make the request from
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    next();
})
app.use(bodyParser.urlencoded({extended: false}));
app.use(bodyParser.json());

all the relevant requirements are inserted earlier in my code too.

Please help me I don’t know what else to doo… D:

Thank you!

my netlify.toml file does not have a capital “N” btw oops!

You simply need to setup a proxy rewrite and the netlify.toml that you’ve share should look like this:

[[redirects]]
  from = "/api/*"
  to = "https://ometer-back.herokuapp.com/:splat"
  status = 200
  force = true

[[redirects]]
  from = "/*"
  to = "/index.html"
  status = 200

Then, in your frontend, you simply need to call the API like:

await axios.post('/api/foo')
// no need for all-those options, however you can use content-type if you want

This request will be forwarded to https://ometer-back.herokuapp.com/foo.

Thank you @hrishikesh … what is a proxy rewrite though?

I looked at the Netlify docs and I got this:

Proxy to another service

Similar to how you can rewrite paths like /* to /index.html , you can also set up rules to let parts of your site proxy to external services. Let’s say you need to communicate from a single-page app with an API on https://api.example.com that doesn’t support CORS requests. The following rule will let you use /api/ from your JavaScript client:

/api/*  https://api.example.com/:splat  200

Now all requests to /api/... will be proxied through to https://api.example.com straight from our CDN servers without an additional connection from the browser. If the API supports standard HTTP caching mechanisms like ETags or Last-Modified headers, the responses will even get cached by our CDN nodes.

Is this essentially the same as you’ve just described in your example there @hrishikesh ?

Thanks for your help :slight_smile:

Yes, it’s the same thing, but in another syntax (_redirects) file. I gave you a netlify.toml approach as you were already using it and managing it all in a single place would make more sense to me.

Hi @hrishikesh , that makes sense to me to. So where you’ve put

from = "/api/*

… does this mean I have to change my API route? currently it’s just “/”

and I would simply call in the front end using

await axios.post("/api/",

Currently your API route seems to be in that environment variable which could be just / as you say, I haven’t checked it. But, with the redirect rule that’s suggested, https://ometer-back.herokuapp.com/ address will be available at the /api/ route. So, when you call /api/foo, the request would be made to https://ometer-back.herokuapp.com/foo and so on.

Got it! So I’ve implemented the changes you suggested… now I am getting this error
xhr.js:210 POST https://competent-mayer-42a09b.netlify.app/api/create 500

Form.js:143 Error: Request failed with status code 500
at e.exports (createError.js:16)
at e.exports (settle.js:17)
at XMLHttpRequest.S (xhr.js:66)

500 Internal Server Error  |  Apigee Edge  |  Apigee Docs … could this be an execution in an edge policy?? @hrishikesh

This has to do with your code on Hekoru. I suppose you’re using Express middleware. Due to the way you’ve now created a rewrite, the code might need some changes. If you’re not sure what exactly to change there, you can post the code here and I can try to take a look.

Usually, it’s something related to the base path of the API that you need to modify.

Hi @hrishikesh , it was an issue with the code in Heroku that needed a rewrite. It’s working successfully now :slight_smile: thanks for your help!