-1

I have the following code:

const { v4: uuidv4 } = require('uuid')
const functions = require('firebase-functions')
const nodemailer = require('nodemailer')
const cors = require('cors')({ origin: true })
const gmailEmail = functions.config().gmail.email
const gmailPassword = functions.config().gmail.password
const mailto = functions.config().gmail.mailto
const mailTransport = nodemailer.createTransport({
  service: 'gmail',
  auth: {
    user: gmailEmail,
    pass: gmailPassword
  }
})

exports.sendMail = functions.https.onRequest((req, res) => {
  cors(req, res, () => {
    const items = req.body.items.forEach(item => (
      `${item.quantity} x ${item.uuid} (${item.name})\n`
    ))
    if (req.method === 'POST') {
      const mailOptions = {
        from: gmailEmail,
        replyTo: gmailEmail,
        to: mailto,
        subject: `Order ${uuidv4()} from ${req.body.name} (${req.body.email})`,
        text: `Order\n\n${items}`
      }
      mailTransport.sendMail(mailOptions)
      res.status(200).send(JSON.stringify({ status: 'OK' }))
    } else {
      res.status(400).send(JSON.stringify({ status: 'method not allowed' }))
    }
  })
})

For some reason it worked once and then keeps giving me

Access to fetch at 'https://xxxxx.cloudfunctions.net/sendMail' from origin 'https://xxxx.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

What am I missing? If possible I'd like to avoid using Express.

kuroneko
  • 425
  • 2
  • 4
  • 10
  • try these in separate statements? const app = express(); const cors = require('cors'); app.use(cors({ origin: true })); – joy08 Mar 24 '20 at 06:18

1 Answers1

0

For you to configure CORS on your Cloud Functions with Firebase, you will need to configure and set some additional parameters - as mentioned in the official documentation here - for CORS to be authorized and execute via HTTP in your application.

The parameters in an example of settings that you will need to configure on your application is the following:

const express = require('express'); 
const cors = require('cors')({origin: true}); 
const app = express(); 
app.use(cors({ origin: true }));

I would recommend you to give it a try using the above setting for you to give the authorization in your backend.

Besides that, the below questions from the Community, there are some other solutions and use cases of similar issues to yours, that I believe should help you achieve the configuration and that I think you should check as well.

Let me know if the information helped you!

gso_gabriel
  • 4,199
  • 1
  • 10
  • 22