CORS policy is preventing preflight requests to Cloud functions using the OPTIONS method

Currently, I am working on a project to develop a basic app where users can upload a .pdf file on the front end. The server will receive the file and process it until it generates a Firebase storage link. The front end is hosted on Firebase Hosting, while the backend is a cloud function built using express. However, an error has been encountered:

CORS policy is blocking access to XMLHttpRequest at 'https://us-central1-paperfire-ada3a.cloudfunctions.net/api/upload' from the origin 'https://paperfire-ada3a.firebaseapp.com'. The preflight OPTIONS method is failing due to lack of 'Access-Control-Allow-Origin' header in the requested resource.

The network tab shows that the preflight OPTIONS method is not successful:https://i.sstatic.net/7W48z.png

I have attempted to set up CORS in various ways by using the cors() package from express or manually setting headers, but none of these methods have worked so far. Interestingly, everything functions properly when testing with Postman, indicating that there might be no other errors in the code. If such errors do exist, identifying them seems challenging at this point. Below is the AJAX call made from the front end:

firebase.auth().currentUser.getIdToken(true).then(function(idToken) {

            var form = $('#uploadForm')[0];
            var formData = new FormData(form);
            //formData.append('file', $('#pdf')[0].files[0]);
            // Perform the AJAX request
            $.ajax({
                type: 'POST',
                url: 'https://us-central1-paperfire-ada3a.cloudfunctions.net/api/upload',
                data: formData,
                contentType: false, // This is required for FormData with file upload
                processData: false, // Also required for FormData with file upload
                headers: {
                    'Authorization': 'bearer ' + idToken,
                },
                success: function(response) {
                    console.log(response.extractedText)

And here is the cloud function:

const functions = require('firebase-functions');
const axios = require('axios');
const cors = require('cors')
const admin = require('firebase-admin');
const { getStorage, ref, uploadBytes, getDownloadURL } = require('firebase-admin/storage');
const express = require('express');
const pdfParse = require('pdf-parse');
const { OpenAI } = require("openai"); 
const openai = new OpenAI({apiKey:'api-key'});
const app = express();
var serviceAccount = require("./something.json");


const MAX_FILE_SIZE = 16 * 1024 * 1024; // 16 MB
admin.initializeApp({
    credential: admin.credential.cert(serviceAccount),
    databaseURL: "databse-url",
    storageBucket: 'bucket-path'
  });

// Configure CORS
const corsOptions = {
    origin: 'https://paperfire-ada3a.firebaseapp.com/', // Adjust the origin according to your needs
    optionsSuccessStatus: 200, // some legacy browsers (IE11, various SmartTVs) choke on 204
    methods: 'GET, POST, DELETE, OPTIONS',
    allowedHeaders: 'Origin, X-Requested-With, Content-Type, Accept, Authorization'
};

app.use(cors(corsOptions)); // Use cors middleware

app.get('/', (req, res) => {
    console.log('I GOT HERE, THE FILE IS:');
    res.send('Welcome to the PDF processing API. Use the /upload endpoint to upload files.');
});

app.post('/upload', async (req, res) => {
    console.log('I GOT HERE, THE FILE IS:');
    const uid = req.headers.authorization.split('bearer ')[1];
    // if (req.method === 'OPTIONS') {
    //     // Send response to OPTIONS requests
    //     res.set('Access-Control-Allow-Methods', 'POST');
    //     res.set('Access-Control-Allow-Headers', 'Content-Type');
    //     res.set('Access-Control-Max-Age', '3600');
    //     res.status(204).send('');
    //   } else {
    //     res.send('Hello World!');
    //   }

    const file = req.body
...
exports.api = functions.runWith(runtimeOpts).https.onRequest(app);

The backend code does not execute due to the failure of the OPTIONS method, leaving me unsure about the next steps to take. Thank you very much for any assistance!

Answer №1

After dedicating several days to investigating, it became clear that the issue did not stem from my cors setup. My cloud function was not being accessed due to Google Frontend blocking my request. I managed to resolve this problem by adjusting permissions for Cloud functions Invoker to allUsers directly from the Google Cloud console. While this serves as a temporary fix, there may be more comprehensive solutions out there. Moving forward, securing this variable in a production environment remains a priority due to the associated security risks.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Form Automatically Submits Data Upon Loading of Page

I am currently facing an issue with my hidden div that is being loaded when I click the submit button. The form is sending results upon page load, and even though I have included the validateForm() function and called it at the end of the submit function ...

Struggling with rendering an HTML element utilizing jQuery's attribute functionality, encountering issues exclusively in Internet Explorer version

I need assistance with generating and inserting an HTML element using jQuery. In my code, I am including a class attribute for the element as shown below: jQuery('<li></li>', { class: "myClass" }); However, when testing in IE ...

What happens when dynamically loaded static resources are loaded?

Currently, I am dynamically injecting HTML into a page using JQuery AJAX. The injected HTML contains script and link tags for JS and CSS files respectively. The issue I am facing is that my initPage() function runs before the script containing its definiti ...

Limitations prevent Express-fileupload from handling large file uploads

I am currently facing an issue while attempting to upload a file of large size (2.75GB). Whenever I try to upload this particular file, the NodeJS server crashes and displays the following errors. However, smaller files are uploaded without any issues. OTL ...

Using Vue to bind a class attribute with multiple Tailwind classes

I am attempting to associate an attribute and multiple tailwind classes with an HTML element. This is specifically for a tab menu where the goal is to dynamically display the title of the "active" tab and apply additional tailwind classes to modify the app ...

What is the best way to incorporate a dropdown menu into existing code without causing any disruption?

I've come across this question multiple times before, but I still haven't found a suitable answer or solution that matches my specific situation. (If you know of one, please share the link with me!) My goal is to create a basic dropdown menu wit ...

React useEffect only retrieves the last element of an array object

I am facing an issue where React seems to only save the last element in my array. Even though I have two elements, when mapping over them, only the last element is being placed in the hook each time. React.useEffect(() => { if (bearbeiten) { handleCli ...

What is the method for showcasing background images sequentially?

css code #intro { position: relative; background-attachment: fixed; background-repeat: no-repeat; background-position: center top; -webkit-background-size: cover; -moz-background-size: cover; backgr ...

What's the trick to efficiently managing multiple checkboxes in an array state?

I have a lengthy collection of checkboxes that is not well optimized. I am trying to obtain the checked ones and store them in an array state. However, I am uncertain about how to handle this situation and I would appreciate some assistance. It should also ...

Tips for clearing Nightwatch session storage efficiently

To ensure the pop-up functionality was working properly, I had to reset the browser's session storage. By doing this, the pop-up will reappear. Is there a way to clear the page's Session Storage in Nightwatch? ...

Package.json failing to enable NodeJS unsafe-perm functionality

Attempting to execute a npm install command with a preinstall script in my package.json. Despite being aware of it being considered an antipattern, I need to run certain scripts as root. The approach works when adding a .npmrc file with the content unsafe ...

Having trouble getting JSON data to display in CanvasJS

I am trying to retrieve JSON data using Ajax with this code. It works fine when fetching data from the original source, but it's not working with my own JSON data. What could I be missing? Any help would be greatly appreciated. Thank you. $(document) ...

Send data from the URL to PHP and then to Javascript in order to showcase the value within an input field

I need to pre-fill an email subscriber form with an email address from the URL. The specific email address is included in the following URL: http://www.domain.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="dcacbdbbb9e3b9b ...

What is the best way to merge two tables together using the server-side JQuery Datatable plugin?

I recently came across an amazing example of a server-side ColdFusion jQuery datatable on this website: Check it out here However, I am facing an issue with adding a second table in the lookup. Specifically, while the primary table lists location_id, I al ...

Using a function as a parameter in Typescript: Anticipated no arguments, received 1.ts

I'm encountering an issue when trying to pass the doSomething function into performAction. The error message I'm receiving is Expected 0 arguments, but got 1 interface SomeInterface { name: string, id: string } function doSomethingFunction( ...

Can you point me to the location where the 'req' parameter is specified?

I've been exploring a new authentication approach detailed in this article. One issue I'm encountering is locating where the req parameter is declared in the snippet below. It seems like my code won't compile because this parameter isn&apos ...

Attempting to establish Node authentication using express and passport

Currently, I'm in the process of developing a straightforward user authentication system using node.js, passport, and express for a scheduled SMS application. However, despite trying various fixes suggested online, I keep encountering the following er ...

Retrieve the earliest and latest dates from a JSON file to utilize with FlatPicker

I have a file in an unknown format, possibly JSON, with dates listed. I am attempting to extract the minimum and maximum dates from this data in MM/DD/YYYY format for use as variables in Flatpicker's minDate and maxDate options. The current AJAX call ...

Guide to writing a unit test for a parameter decorator in NestJs

I want to implement a unit test for a basic custom decorator that I created, but I'm facing some challenges. This decorator was developed based on the solution provided here. I have Keycloak authentication set up and using this solution in my controll ...

Eliminating Repetitions in Array of Objects by Filtering Out Objects with Matching Properties

I am currently working with an array of objects where I need to identify duplicates based on specific properties (first and last names). Below is my attempt at solving this issue: The expected output should resemble: [ {first:"John", last: "Smith", id: ...