When I try to send an email using nodejs and node mailer, sometimes it sends the email, but sometimes it throws the following error below:
Access to XMLHttpRequest at 'https://nodejsmailer' from origin 'https://org' has been blocked
by CORS policy: Response to preflight request doesn't pass access control check:
No 'Access-Control-Allow-Origin' header is present on the requested resource.
This is my jQuery code:
function SendEmail() {
$.ajax({
contentType: 'application/json',
url: "https://nodejsmailer",
type: "POST",
body: JSON.stringify({
'to': to,
'body': body,
'subject': subject
}),
headers: {
"Accept": "application/json;odata=verbose",
'Access-Control-Allow-Origin':'*',
"content-type": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val()
},
success: function(data) {
console.log(data);
},
eror: function(data) {
console.log(data);
}
})
}
This is my node js code:
const express = require('express');
var nodemailer = require('nodemailer');
var qs = require('qs');
const cors = require("cors");
const app = express()
app.use(cors());
const port = 5000;
app.use(express.json());
app.post('/sendemail', (req, res) => {
var options = {
from: 'noreply@somewhere.com',
to: req.body['to'],
subject: req.body['subject'],
text: req.body['body']
};
res.set('Access-Control-Allow-Origin', '*');
transporter.sendMail(options, function(error, info) {
if (error) {
res.end(error);
} else {
res.setHeader('Content-Type', 'text/plain');
res.end('Email sent.\n');
}
});
});
What could be causing this issue? Could it be because I am behind a proxy?