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

Get the data from the files in the request using request.files in Node.js

Is there a way to read the content of a file (either a txt or CSV file) that a user uploads without saving it to local storage? I know I can save the file in an upload directory and then read it from storage. However, I'm wondering if there is a way ...

Concealing a Specific Element with Text using jQuery

Is there a way to conceal the section that includes the element labeled as "Product Tags" on a webpage? ...

Utilizing the $(this).text method in combination with the content class

In order for the text of the click function to be the final variable, I attempted using $(this).text, but unfortunately it did not produce the desired outcome. Placing the class at the end resulted in both p lines appearing. My goal is to only display the ...

Uploading videos to a single YouTube channel using the YouTube Data API

I have been tasked with creating a node js app for a select group of individuals who need to upload videos. However, our budget is quite limited and we are unable to afford cloud storage services. I am curious if it would be feasible to create a key syste ...

Transform JSON structure (Group data)

Here is the JSON object I am working with: [{ "name" : "cat", "value" : 17, "group" : "animal", }, { "name" : "dog", "value" : 6, "group" : "animal", }, { "name" : "snak", "value" : 2, "group" : "animal", }, { "na ...

Switching the navigation menu using jQuery

I am looking to create a mobile menu that opens a list of options with a toggle feature. I want the menu list to appear when the toggle is clicked, and I also want to disable scrolling for the body. When the toggle menu is clicked again, the list should c ...

Steps to Utilize Google Apps Script from a Website

I've been on a mission to find the solution to my problem. I have a basic web page with HTML/CSS/JS. What I want is for users to visit the page and immediately have it call up a Google script I created, which will pull information from a spreadsheet a ...

Utilizing multiple routers in Express middleware for Node.js

How do I successfully display my data from mongoDB that is organized into collections? I am able to access the data individually, but encounter difficulties when trying to retrieve them collectively. Here is an example of how my code is structured: Within ...

What are the steps to implementing PNG masking using PixiJS?

I am currently working on incorporating a png sprite as a mask for another layer. I found a demo on the pixi.js official website and created this fiddle: https://jsfiddle.net/raphadko/ukc1rwrc/ The code snippet below is what I am using for the masking fu ...

Angular.js fails to load successfully every other time

My angular application is running into some issues with bower. At times, when I start up the server, I encounter the following error: Uncaught Error: [$injector:modulerr] Failed to instantiate module myApp due to: Error: [$injector:modulerr] Failed to in ...

the dropdown menu toggle is not working as expected

My dropdown icon is not appearing and the menu options are not functioning properly. Despite trying to use a script to display the text when an option is clicked, it doesn't seem to be working. It appears that the toggle functionality is not working ...

Outputting JSON data from a MySQL database using the Express framework

I've successfully created a database in MySQL. mysql> SELECT * FROM test456; +-----+-------+-------------------------+ | _id | name | image | +-----+-------+-------------------------+ | 1 | Chris | /home/images/index.jpeg | +- ...

How to determine button placement based on the content present on the page

I'm struggling to find the right CSS positioning for a button on my page. I want the button to stay fixed in a specific location, but when there's a lot of content on the page, I need it to adjust its position accordingly. Initially, I want the ...

Ways to retrieve object in Javascript

I retrieved this data object from a JSON file source. { "Apple": "Red", "Orange": "Orange", "Guava": "Green", } Afterward, I transformed it into an Object using: var data = JSON.parse(dataFromJson); which resulted in a JavaScript object ...

Perform an ajax POST call to a server using ajax/jQuery techniques

I am attempting to utilize ajax to send a post request to a different domain and receive a json response. The server is located within my company premises and the logs show that it is indeed sending back a json response. Below are two samples of my attemp ...

Utilize Javascript to Populate Form Fields Based on "Selected Name"

I am currently facing a challenge in using javascript to automatically populate a form, specifically when it comes to setting the value for the country field. <form action="/payment" method="post" novalidate=""> <div class="input_group"> ...

There is no valid injection token found for the parameter 'functions' in the class 'TodosComponent'

While working in my code, I decided to use 'firebase' instead of '@angular/fire'. However, I encountered an issue that displayed the following error message: No suitable injection token for parameter 'functions' of class &apos ...

Instead of only one menu icon, now there are three menu icons displayed on the screen. (Additionally, two more divs containing

When visiting on a smartphone browser, you may notice that instead of one menu icon, three icons appear. Upon inspecting the elements, you will find that there are three div's that look like this: <div class="responsive-menu-icon">&l ...

Guide to developing JavaScript code that moves information from one local website to a different one

Here's the scenario: You input text into a field on website A and click a button. Upon clicking that button, the entered text should appear in website B. I attempted to use localStorage for this functionality, but unfortunately it was not successful. ...

Omitted Script within a Node.js JavaScript Code Segment

My code snippet is: function write_to_orchestrate(data_to_write) { console.log('more testing'); db.put('musician', '1', '{"test":"test1"}') .then(function (result) { res.send(result); ...