Is there a way to fix the error "The requested resource does not have the 'Access-Control-Allow-Origin' header" within Express using Firebase functions?

Trying to send an email through nodemailer using Firebase functions, but encountering errors. The data for the email will come from a form.

Error message: Access to XMLHttpRequest at 'my-firebase-functions' from origin 'my-angular-web-app' has been blocked by CORS policy due to no 'Access-Control-Allow-Origin' header presence on the requested resource.

Below is my Firebase functions configuration:

app.use((req, res, next) => {

    // Define allowed origins
    res.setHeader('Access-Control-Allow-Origin', 'https://stanleyogbonna-5228d.web.app');
    res.setHeader('Access-Control-Allow-Origin', 'https://stanleyogbonna-5228d.firebaseapp.com');

    // Define allowed HTTP methods
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');

    // Define allowed request headers
    res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type,Content-Type');

    // Allow credentials to be included in requests
    res.setHeader('Access-Control-Allow-Credentials', true);

    // Move to next layer of middleware
    next();
});

// Gmail account credentials
const gmailEmail = functions.config().gmail.login;
const gmailPassword = functions.config().gmail.pass;
admin.initializeApp();

app.post('/visitor/contact', (req, res, next) => {

    // Create transporter for sending emails
    const transporter = nodemailer.createTransport({
        service: 'gmail',
        auth: {
            user: gmailEmail,
            pass: gmailPassword
        }
    });

    // Email content
    const mailOptions = {
        from: gmailEmail,
        to: req.body.email,
        subject: 'Full stack developer',
        html: `<h1 style="color:blue;">Welcome ${req.body.firstName}</h1>
               <p style="font-size:25px;">Thank you very much for contacting me. i hope you are 
having a great time where ever you may be.</p>
            <p style="font-size:25px;">I am a full stack developer by training and i am available at the moment for a MEAN stack job That will challenge me to be better.</p>
            <p style="font-size:23px;">Thanks ${req.body.firstName}</p>`
    };

    transporter.sendMail(mailOptions);
})


// Handle 404 error
app.use((req, res, next) => {
  next(createError(404));
});

// Error handler
app.use((err, req, res, next) => {
  // Set error message and provide error details only in development mode
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // Render the error page
  res.status(err.status || 500);
  res.render('error');
});

exports.app = functions.https.onRequest(app);

Answer №1

To resolve the CORS issue, it is recommended to utilize the cors package. Ensure that you have set up cors in your Node environment. I can demonstrate how I incorporate cors into my Firebase cloud function for sending emails. Instead of using nodemailer, I opt for sendgrid. I will illustrate how you can integrate cors into your functions by sharing my code snippet which exemplifies my usual method of including cors.

exports.sendEmail = functions.https.onRequest((req, res) => {
  if (!req.body) return res.sendStatus(400);
  return cors(req, res, () => {
    var to = req.body.to;
    var from = req.body.from;
    var sender_name = req.body.sender_name;
    var message = req.body.message;
    var pkgname = req.body.pkgname;
    var html = "<h2>" + sender_name + "</h2>" + message;
    const sgMail = require("@sendgrid/mail");

    const subject = "Pre registration - " + pkgname + " - " + sender_name;
    sgMail.setApiKey(
      "sendgrid api key"
    );
    const msg = {
      to: to,
      from: from,
      subject: subject,
      html: html,
    };
    sgMail.send(msg, (sendError, sendRes) => {
      if (sendError) return res.status(500).send(sendError);
      else return res.status(200)(sendRes);
    });
  });
});

Just a heads up – sendgrid comes with no cost!

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

How can you sift through an array of objects by looking at the elements within another nested array? Are you utilizing Vanilla JS, lodash, or another tool from the

Hey, I'm currently working on a React app where I have a list of projects that are associated with specific technologies. What I want to achieve is allowing the user to select certain technologies using checkboxes and have the project list automatical ...

Tips for parsing a JSON object efficiently

Javascript var obj = { "name" : ["alex","bob","ajhoge"], "age" : [30,31,33] }; To display the value "alex," you can use: document.write(obj["name"][0]) But how can we filter through 'obj' to retrieve all data like this? html <ul ...

Navigating with Google Maps and Its Pointers

I've successfully integrated a JSON array of Marker positions into a Google map. Each marker has an associated infoWindow, which is also functioning as expected. However, I'm encountering an issue where clicking on a marker only displays the in ...

Hyphens make Tablesorter sort numeric fields uniquely

I have a table where data is displayed in the format of YYYY-####. Sometimes, there are values like 2012-456 and 2012-1234. By default, the sorting places 2012-1234 before 2012-456. If I change the sort to 'numeric', it disrupts the order of othe ...

No files' links were found in the array in Mongodb following asynchronous operations

When working with my Apollo mutation function, I encounter a situation where two arrays of files are passed as arguments. These files are then written into the filesystem, and their locations are stored in arrays. However, when trying to write these arra ...

What is the best way to create a dynamic graph in amcharts during runtime?

Below is the code for Multiple Value Axes: In this code, we aim to display a graph using dynamically generated random data. When executed, nothing will happen. <script> var chart; var chartData = []; // generate some random data within a different ...

Modifying the height of the bar in Google Charts Timeline using react-google-charts

I am currently working on a Google Chart timeline using react-google-charts. <Chart chartType="Timeline" data={data} width="100%" options={{ allowHtml: true bar: { groupWidth: 10 }, }} ...

Is it possible to include two of these on a single page with unique variables? (Using JQuery)

I am looking to create two similar pages, each with different percentages. However, when I try modifying the JS or changing class/ID names, it keeps pulling data from the first SPAN element. http://jsfiddle.net/K62Ra/ <div class="container"> <di ...

Having trouble removing the npm package spotifydl from my system

After running the command npm install -g spotifydl, I discovered that the package was obsolete and no longer functioning properly. Subsequently, I attempted to remove it using npm uninstall -g spotifydl, but instead of completely uninstalling, it kept re ...

Issue with a Firebase and React tutorial

Currently, I am in the process of learning Firebase and React to create a single-page-application that retrieves data from a Realtime Database hosted on Firebase. I am following a tutorial by Google/Firebase where they explain how to start with Firebase a ...

Activate the audit command for the npm enterprise registry

I'd like to know how to activate the npm audit command in my npm enterprise registry. Whenever I attempt to run the npm audit command, I encounter the following error: { "error": { "code": "ENOAUDIT", "summary": "Your configured registry ( ...

Yet another error encountered: "Headers cannot be set after they have already been sent to the client" when submitting the form

Whenever I try to submit text to a single-field form on my node.js server, I encounter the following error: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client at ServerResponse.setHeader (_http_outgoing.js:485:11) ...

Encountering a TypeError when using the react useRef() hook

During my work on an app utilizing the webRTC API and working with the useRef() hook in React, I encountered an error Error: TypeError: myVideo.current is undefined ContextProvider SocketContext.js:27 promise callback*ContextProvider/< SocketCon ...

This code snippet results in the property being unrecognized

I recently wrote this block of code and encountered an error while trying to run the alert function. It keeps telling me that 'this.words' is not defined. I suspect the issue lies within the jQuery portion, as I am able to access the array where ...

Tips on incorporating personalized javascript functions into Durandal

I am currently working on my first project using the Durandal framework to create a basic website. I have encountered an issue while trying to incorporate a simple JavaScript function. My goal is to execute the function after the DOM has loaded, but I am u ...

Attempting to insert a line break tag within the text using React

Having trouble inserting line breaks in text using React. Can anyone guide me on how to achieve this? I've attempted adding the br tag, but it is displaying as in the browser. Here's a snippet of my code. Appreciate any help or advice. let sp ...

Modify the colors of <a> elements with JavaScript

I am brand new to the world of UI design. I am encountering an issue with a static HTML page. (Please note that we are not utilizing any JavaScript frameworks in my project. Please provide assistance using pure JavaScript code) What I would like to achie ...

Select elements from a PHP loop

As part of my school project, I am developing a basic webshop. Currently, I am using a while loop to display featured products on the homepage. However, I now need to implement a shopping cart functionality. After a user clicks the "add to cart" button, th ...

Lack of communication between Node.js modules

Currently, I am diving into the world of node.js as part of a personal project to enhance my skills. To maintain best practices, I have been segmenting my code into different modules. However, I have hit a roadblock where a module I created is not communic ...

performing asynchronous iteration with HTTP PUT requests

I'm attempting to send multiple HTTP PUT requests to my server, but I am only able to successfully send one JSON object to the database. What could be missing in my code? var data1 = JSON.stringify(require('./abc.json')), data2 = JSON ...