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?