Quantcast
Channel: Active questions tagged rest - Stack Overflow
Viewing all articles
Browse latest Browse all 4118

No 'Access-Control-Allow-Origin' - CORS error

$
0
0

I built a tiny api to help me send emails from my front end to my gmail inbox.I have installed cors, express and dotenv as dependencies to build this api.

const express = require("express");const emailjs = require("@emailjs/browser");const cors = require("cors");const app = express();require("dotenv").config({  path: `.env`,});app.use(express.json());app.use(cors());const PORT = process.env.PORT;app.post("/api/send_email", async (request, response) => {  console.log(request.body);  const { senderEmail, senderName, emailSubject, message } = request.body;  const service_id = process.env.REACT_APP_SERVICE_ID;  const template_id = process.env.REACT_APP_TEMPLATE_ID;  const user_id = process.env.REACT_APP_USER_ID;  const public_key = process.env.REACT_APP_PUBLIC_KEY;  const templateParams = {    to_name: "Cora",    from_name: senderName,    from_email: senderEmail,    message: message,    subject: emailSubject,  };  try {    response.set("Access-Control-Allow-Origin", "*");    emailjs      .send(service_id, template_id, templateParams, public_key)      .then(() => {        response.status(201).send({ msg: "Message sent!" });      });  } catch (error) {    console.error(error);    response.status(500).send({ error: "Internal Server Error" });  }});app.listen(PORT, () => {  console.log(`Server is online, listening on port ${PORT}...`);});

I went online after the following error showed up in my console:

/contact:1 Access to XMLHttpRequest at 'https://contact-functionlity.onrender.com/api/send_email' from origin 'https://alfredo-galvez.netlify.app' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

and in most videos I saw on youtube mentioned installing cors and use it in your app, which is what I have done.I also tried setting up the response headers using:

app.use(cors({    origin: 'https://alfredo-galvez.netlify.app'}))

I am a little bit stuck and have been trying to understand what is going on for a quite a while now, wondering is someone could help me out.


Viewing all articles
Browse latest Browse all 4118

Latest Images

Trending Articles



Latest Images

<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>