How to configure CORS

How to configure CORS
0

Hi, folks. I’m working on my developer portfolio, hosting it on Netlify, which is front-end only. I want to have a contact form that sends me an email, so I set up an API endpoint with Node, hosted on Heroku, to accomplish this. Unfortunately, when I try to send a post request to the API, I get an error:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://myapiendpoint.herokuapp.com. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).

I’m finding lots of information on why this is happening, but I can’t seem to find anything on how to actually go about configuring my server to allow requests from my portfolio site. If anyone can explain how to do this, it’d be much appreciated.

Well, this was one of those situations where you find the solution right after posting.
For anyone else running into this issue in the future, here’s what I had to do on the server.
Download and require the “cors” module.

npm install cors
const cors = require('cors');

Then add cors() as a parameter to your desired route.
app.post("/email", cors(), (req, res) => {stuff}

This gives open access to your endpoint.
You can give permission to a single site by passing some parameters as an argument to cors().

var corsOptions = {
  origin: 'http://example.com',
  optionsSuccessStatus: 200 // some legacy browsers (IE11, various SmartTVs) choke on 204
}