0

I am trying to communicate to my cloud function from a chrome plugin. Everything works fine if i don't enable authentication in the cloud function console. But when i enable only authenticated user then I get the following error

Access to XMLHttpRequest at 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

My Ajax code

 return new Promise((resolve, reject) => {

    $.ajax({
      url : API_ENDPOINT+'method4',
      method : 'POST',
      beforeSend: function (xhr) {
          xhr.setRequestHeader('Authorization', 'Bearer '+firebase.auth().currentUser._lat);
      },
      data : 'id='+id,
      success: function(data, textStatus, xhr) {
          console.log(data);
          resolve(data);
      },
      error: function(data, textStatus, xhr) {
          reject(data);
          console.log(data)
      },
  });

});

Below is my Function code deployed on cloud function

exports.method4 = functions.https.onRequest((request, response) =>{

    response.set('Access-Control-Allow-Origin', 'chrome-extension://pcpjkilopmjdhcigjjndndibccdingcb');
    response.set('Access-Control-Allow-Credentials', 'true');

    if (request.method === 'OPTIONS') {

      // Send response to OPTIONS requests
      response.set('Access-Control-Allow-Methods', 'GET, POST');
      response.set('Access-Control-Allow-Headers', 'Authorization');
      response.set('Access-Control-Max-Age', '3600');
      response.status(204).send('');

    } else {

      if (request.method !== 'POST') {
        // Return a "method not allowed" error
        return response.status(405).end();
      }

      return response.send(request.body['id']);

    }
})

I am stuck with this for the past 2 days and not sure what is causing this issue. Thanks in advance.

1 Answer 1

0

It seems like your problem is because of the OPTIONS method you are using. As you can see here, the only HTTP methods supported by Google apps scripts web-application are POST and GET and OPTIONS method is currently not supported.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.