Cloud Functions for Firebase triggering function on CORS preflight request

后端 未结 1 711
难免孤独
难免孤独 2021-02-06 08:59

I have a cloud function that validates inputs from a form submission on my client. I\'m using Cloud Functions for Firebase https triggers with cors express middleware.

相关标签:
1条回答
  • 2021-02-06 09:18

    To fix the duplicate requests 200 and 204 then change how you're client side fetch request. @sideshowbarker is right. The browser automatically does the CORS preflight OPTIONS request so this is not an issue in Cloud Functions for Firebase. This answer was helpful.

    To fix the preflight I changed my code to the following:

    Client Call To Function

    Removed the headers from the fetch options completely rather than setting the content type as application/json. By default the fetch request content type is application/x-www-form-urlencoded; charset=UTF-8.

    const validateImageFormFetchOptions = {
      method: 'POST',
      body: JSON.stringify({
       formInputs: formInputs
      })
    }
    
    fetch('https://project-url.cloudfunctions.net/apiValidateImageForm', validateImageFormFetchOptions)
      .then(response => response.json())
      .then(serverErrors => {console.log(serverErrors)});
    

    Firebase Function

    Explicitly parsed the request body because it is now received as a text string.

    const functions = require('firebase-functions');
    const express = require('express');
    const cors = require('cors')({origin: true});
    const validateImageForm = require('./library/validate-image-form');
    
    exports.apiValidateImageForm = functions.https.onRequest((req, res) => {
      cors(req, res, () => {
        const body = JSON.parse(req.body);
        validateImageForm(body.formInputs, body.imageStatus).then((data) => {
          res.status(200).send(data);
        });
      });
    });
    
    0 讨论(0)
提交回复
热议问题