0

I try to solve an issue in my node backend server to get an email system with react for frontend done. I already installed cors but I get the error which says Cross-origin request blocked. I´m struggling for hours now but I can´t get on how to fix this.

This is my backend code including cors:

const express = require('express');
const app = express();
require('dotenv').config();

const bodyParser = require('body-parser');
const cors = require('cors');
const nodemailer = require('nodemailer');

app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

app.use(cors());

app.post('/send_mail', cors(), async (req, res) => {
  let { text } = req.body;
  const transport = nodemailer.createTransport({
    host: process.env.MAIL_HOST,
    port: process.env.MAIL_PORT,
    auth: {
      user: process.env.MAIL_USER,
      pass: process.env.MAIL_PASS,
    },
  });

  await transport.sendMail({
    from: process.env.MAIL_FROM,
    to: 'test@test.com',
    subject: 'test email',
    html: `<div className="email" style="
        border: 1px solid black;
        padding: 20px;
        font-family: sans-serif;
        line-height: 2;
        font-size: 20px; 
        ">
        <h2>Here is your email!</h2>
        <p>${text}</p>
    
        <p>All the best, Darwin</p>
         </div>
    `,
  });
});

app.listen(
  (process.env.PORT || 4000,
  () => {
    console.log('Server is listening on port 4000');
  })
);

and here is my frontend code:

import axios from 'axios';
import React, { useState } from 'react';

const Mailer = () => {
  const [sent, setSent] = useState(false);
  const [text, setText] = useState('');

  const handleSend = async (e) => {
    setSent(true);
    try {
      await axios.post('http://localhost:4000/send_mail', {
        text,
      });
    } catch (error) {
      console.log(error);
    }
  };

  return (
    <div className='Mailer'>
      {!sent ? (
        <form onSubmit={handleSend}>
          <input
            type='text'
            value={text}
            onChange={(e) => setText(e.target.value)}
          />
          <button type='submit'>Send </button>
        </form>
      ) : (
        <h3>Thanks for your message</h3>
      )}
    </div>
  );
};

export default Mailer;

I don´t find the error, does somebody see the problem?

Ted13x
  • 33
  • 1
  • 4

2 Answers2

0

Sometimes, CORS errors could be as a result of regular backend errors, and not actually CORS.

Looking at your code, the first thing I will check would be to make sure that the env variables are actually getting the values they should get.

Also, make sure you nest your sendEmail method in a try catch block, and try to log out any error the server may have

unhackit
  • 543
  • 3
  • 9
  • I checked the env file, everything is right here. This is a very simple mail server, I don´t know which kind of errors I should check. – Ted13x Jul 28 '21 at 08:54
-1

To enable cors with express see: https://enable-cors.org/server_expressjs.html

In axios: Access Control Origin Header error using Axios in React Web throwing error in Chrome

user3682770
  • 125
  • 1
  • 1
  • 7