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!