Home > Net >  CORS errors as a result of moving function into separate JS class
CORS errors as a result of moving function into separate JS class

Time:10-22

I have a button which sends an API bug report, however I recently moved it from Main.js into into its own class, and suddenly I receive CORS errors among others whenever I attempt to use it. I've done some research but I can't understand why this would be triggered simply by moving the function into its own class, looking for guidance as to why this behaviour might happen and how to avoid it.

Errors:

Uncaught (in promise) TypeError: response.json is not a function
Access to fetch at 'exampleUrl' from origin 'http://localhost:4567' has been blocked by CORS policy: Request header field token is not allowed by Access-Control-Allow-Headers in preflight response.
Uncaught (in promise) TypeError: Failed to fetch

 $("#bugForm").submit((e) => {
        e.preventDefault()
        const input = document.getElementById('nameInput');
        // logic here
        const bugInfo = {
          info: "Hello"
        }
        Logger.logInfo(bugInfo).then(console.log('print'))
      })
    });

Logger.js

   class Logger {

   constructor(settings) {
   // getting the settings here and assigning it to the constructor variable
     this.settings = settings;
   }
   static async logInfo(data = {}) {
     console.log('Hello!')
     const url = 'https://www.pivotaltracker.com/services/v5/projects/2530461/stories'
     const response = fetch(url, {
       method: 'POST',
       headers: {
         "Token": `${metadata.settings.token}}`,
         "Content-Type": "application/json"
       },
       body: JSON.stringify(data)
     });
     return response.json();
   }
 }

 const metadata = {
   settings: "Hello"
 }
 const logger = new Logger(metadata.settings);

Code before the move into new class:

 async function reportBug(data = {}) {
  const url = 'urlexample'
  const response = await fetch(url, {
    method: 'POST',
    headers: {
      "X-TrackerToken": `${metadata.settings.token}`,
      "Content-Type": "application/json"
    },
    body: JSON.stringify(data)
  });
  return response.json();
}

enter code here

CodePudding user response:

No, this has most likely nothing to do with moving your function to another class.

But first of all, you are using fetch wrong

const response = fetch(url, { ...});

returns a promise. You have to wait until it resolves or rejects, until you can try accessing its body. Ie, you can't just do

return response.json()

because a Promise doesn't have a method json() (as the first error tells you). You have to either use .then(...).catch(...) or await. For instance

return fetch(...)
  .then(response => {
    if (response.ok) //check if httpstatus is 2xx
      return response.json();

    throw new Error(`status ${response.status`);
  } 

But be aware that this will also return a Promise (as response.json() is again async and returns a promise), which you have to wait for. And (at some) point you have to .catch() the errors from rejected promises (that's what the third error is telling you, your fetch ran into some error you are not catching) Grab one of the thousands of tutorials about async programming and rework your code.

The second error is telling you, that the answer from that server is missing a specific header definition from the Access-Control-Allowed-Headers header. (and that's most likely causing your fetch to fail). Ie you are sending a Token header to the server which is not allowed by the server. So, if you said it worked before moving the code, you probably didn't have that header before and added it shortly after moving the code. Although I'm not really sure, how that incorrect async programming would have worked ...

  • Related