Home > Software design >  CORS error despite changing Access-Control-Allow-Methods with CORS middleware when deployed in Herok
CORS error despite changing Access-Control-Allow-Methods with CORS middleware when deployed in Herok

Time:05-18

I'm running one client local server with "VSC's Live servers" on localhost:5500, and I'm running a remote server using heroku.

Here is the relevant code regarding the AJAX call client-side when submitting a form:

const xhr = new XMLHttpRequest();
      xhr.open("POST", "https://git.heroku.com/morning-falls-52888.git");
      xhr.setRequestHeader("Content-Type", "application/json");
      xhr.send(JContactRequest);
      xhr.onload = () => {
        const status = xhr.status;
        if (status >= 200 && status < 300 ) {
          $("form").append("<p id='submit-message' style='text-align:center;'>Thank you for your submission!</p>");
        } else if (status == 418 ) {
          window.alert(`Error: ${xhr.status}\nCannot brew coffee, I am a teapot.`);
        } else {
          console.log(`Before append ${status} ready state: ${xhr.readystate}`);
          $("form").append("<p id='submit-message' style='text-align:center;'>Submission Failed</p>");
          console.log(`After append ${status} ready state: ${xhr.readystate}`);
        }
      }

And here is the code server side:

require('dotenv').config();
const express = require('express');
const app = express();

app.use(express.json());

const PORT = process.env.PORT ||4500;
const cors = require("cors");


app.use(cors());

app.listen(PORT, () => { console.log(`Listening on PORT: ${PORT}`) });

// app.use((req,res,next)=>{
//   res.status(404).send('this is working');
// })

app.get('/', (req, res) => {
  res.header("Access-Control-Allow-Methods", "GET,PUT,POST,DELETE,OPTIONS");
  res.status(201).send();
  console.log("received get request");
})

app.post('/', (req, res) => {
  var body=req.body;
  console.log(body);
  
  for(let [key,value] of Object.entries(body)){
    if(value==""){
      res.status(400).send(`Empty Field in ${key}`);
      res.end();
      break;
    }
  }
  var email = body.emailfield;

  if (body.comment == "Can you brew coffee?") {
    res.status(418).send();
  } else {
    res.status(200).send('message sent');
  }
  // calling the api
  const sgMail = require('@sendgrid/mail');
  sgMail.setApiKey(process.env.SENDGRID_API_KEY);
  const msg = {
    to: email,
    from: '[email protected]', // Use the email address or domain you verified above
    templateId:'*************************************',
    dynamic_template_data:body,
  }
  //ES6
  sgMail
    .send(msg)
    .then(() => {}, error => {
      console.error(error);

      if (error.response) {
        console.error(error.response.body)
        console.log(process.env.SENDGRID_API_KEY)
      }
    });
});

The message I'm getting on my console is the following:

Access to XMLHttpRequest at 'https://git.heroku.com/morning-falls-52888.git' from origin 'http://127.0.0.1:5500' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

I'm kind of stumped because I would have thought that app.use(cors()) would have access-control-allow-origin=*.

I'm still very new to this, so any help is mighty appreciated. Thanks!

EDIT I just wanted to add that this code was running fine when I was running the server locally on port 4500

CodePudding user response:

xhr.open("POST", "https://git.heroku.com/morning-falls-52888.git");

You're making an HTTP request to Heroku's Git repo, not to your application running on Heroku (which will have a URL like https://APPLICATION_NAME.herokuapp.com/something)

The CORS permissions have to be granted for the URL you are making the request to, not one that is loosely adjacent to it.

CodePudding user response:

You can add this header in your client side

    "Access-Control-Allow-Origin": "*",

Or

You can configure cors on your server side as per the domains you want to allow access

var allowedDomains = [
   "https:/exampledomain.com",
   "http://localhost:3000",
];
app.use(
  cors({
    origin: function (origin, callback) {
    if (!origin) return callback(null, true);
    if (allowedDomains.indexOf(origin) === -1) {
        var msg = `This site ${origin} does not have an access. Only 
        specific domains are allowed to access it.`;
        return callback(new Error(msg), false);
       }
    return callback(null, true);
   },
  })
 );
  • Related