I have got 'blocked by CORS policy' error as mentioned below. I know this kind issue is reported in this portal many time. As suggested in one of the answers in this portal, I have used cors header 'Origin' with my frontend url. Please refer app.use statement in my server.js file. I am still getting same 'blocked by CORS policy' error. I am not facing this issue when is use postman. Can anyone please assist?
Note: In the frontend fetch statement, i used 'mode:'no-cors'. It helps me to avoid the below error. But, my response from backend becomes opaque response. As mentioned in another post(Handle response - SyntaxError: Unexpected end of input when using mode: 'no-cors') in this portal, opaque response is probably because effect of setting no-cors mode is essentially to tell browsers, “Don’t let frontend JavaScript code access the response body or headers under any circumstances.”. So, i am not able to read the response(comes from backend) in my front end. I have tried with "mode:'cors'" as well as without mode statement also, no luck to fix this issue.
Error:
Access to fetch at 'https://xxxxxx-xxxxxxx.el.r.appspot.com/signup/xxxxxxxxxxxxxx' from origin 'https://xxxxxxxxxxx-frontend.xxxx.r.xxxxxx.com' 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. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
My back-end(Node js): Server.js file
const bodyParser = require('body-parser');
const routesHandler = require('./routes/handler.js');
// Imports the Google Cloud client library for Bunyan.
const lb = require('@google-cloud/logging-bunyan');
// Import express module and create an http server.
const express = require('express');
const cors = require('cors');
app.use(cors({
origin: 'https://xxxxxxsale-frontend.el.r.xxxxxxx.com'
}));
async function startServer() {
const {logger, mw} = await lb.express.middleware({
logName: 'samples_express',
});
const app = express();
app.use(bodyParser.urlencoded({extended:false}));
app.use(bodyParser.json());
app.use('/', routesHandler);
// Install the logging middleware. This ensures that a Bunyan-style `log`
// function is available on the `request` object. This should be the very
// first middleware you attach to your app.
app.use(mw);
// Setup an http route and a route handler.
app.get('/', (req, res) => {
req.log.info('this is an info log message');
res.send('hello world 1');
});
const port = process.env.PORT || 8080;
// `logger` can be used as a global logger, one not correlated to any specific
// request.
logger.info({port}, 'bonjour');
// Start listening on the http server.
const server = app.listen(port, () => {
console.log(`http server listening on port ${port}`);
});
app.get('/shutdown', (req, res) => {
res.sendStatus(200);
server.close();
});
}
startServer();
My back-end(node js): handler.js file
const app = express()
const router = express.Router();
const {getAuth} = require('firebase-admin/auth')
require("dotenv").config()
const bodyParser = require("body-parser")
const nodemailer = require("nodemailer");
app.use(bodyParser.urlencoded({ extended: true }))
app.use(bodyParser.json())
router.get('/addtweets', (req, res) => {
const str = [
{
"name": "Codr Kai",
"msg": "This is my first tweet!",
"username": "codrkai"
},
{
"name": "Samantha Kai",
"msg": "React JS is so simple!",
"username": "Arun"
},
{
"name": "John K",
"msg": "Sweep the leg!",
"username": "johnk"
}
];
res.end(JSON.stringify(str));
});
router.post('/signup/:emailId',function (req, res) {
let useremailT = req.params.emailId;
console.log(req.body);
//const pass = req.body.password;
let spc1=useremailT.indexOf(" ");
let len1=useremailT.length;
pass = useremailT.substr(0,spc1);
useremailT = useremailT.substr(spc1+1,len1-spc1-1);
let spc2=useremailT.indexOf(" ");
len1=useremailT.length;
let useremail = useremailT.substr(0,spc2);
let username = useremailT.substr(spc2+1,len1-spc2-1);
var admin = require("firebase-admin");
var serviceAccount = require("../xxxxxxsales-19e4e-firebase-xxxxxx-xxxxx-xxxxxxxx-xxxxxx.json");
if (!admin.apps.length) {
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
origin:'*'
});
}
getAuth()
.getUserByEmail(useremail)
.then((userRecord) => {
// See the UserRecord reference doc for the contents of userRecord.
//console.log(`Successfully fetched user data: ${userRecord.toJSON()}`);
if (userRecord.emailVerified) {
//console.log('Res 1:' , res);
res.send({"message":"Exist"});
} else {
//console.log('Res 2:' , res);
res.send({"message":"Pending"});
}
})
.catch((error) => {
getAuth()
.createUser({
email: useremail,
emailVerified: false,
password: pass,
disabled: false,
displayName:username
})
.then((userRecord) => {
username = userRecord.displayName;
//console.log('in Error before generateEmailVerificationLink');
getAuth()
.generateEmailVerificationLink(userRecord.email)
.then((link) => {
// Construct email verification template, embed the link and send
// using custom SMTP server.
// return sendCustomVerificationEmail(useremail, displayName, link);
//console.log(link);
var email = userRecord.email;
res.send({link});
})
.catch((error) => {
// Some error occurred.
console.log('error 1:' +error);
//res.end('Error');
res.send({"message":"Error"});
});
})
.catch((error) => {
console.log('error 2:' +error);
//res.end('DBissue');
res.end({"message":error});
//res.send({"message":error});
});
});
});
router.post('/resendEmail', (req, res) => {
const useremail = req.body.email;
var username = ''
var admin = require("firebase-admin");
var serviceAccount = require("../xxxxxxsales-19e4e-firebase-xxxxxx-xxxxx-xxxxxxxx-xxxxxx.json");
if (!admin.apps.length) {
admin.initializeApp({
credential: admin.credential.cert(serviceAccount)
});
}
getAuth()
.getUserByEmail(useremail)
.then((userRecord) => {
// See the UserRecord reference doc for the contents of userRecord.
//console.log(`Successfully fetched user data: ${userRecord.toJSON()}`);
if (userRecord.emailVerified) {
res.end(JSON.stringify('Exist'));
} else {
username = userRecord.displayName;
getAuth()
.generateEmailVerificationLink(userRecord.email)
.then((link) => {
var email = userRecord.email;
res.send({"message":"Registered"});
send_mail(link,userRecord.email,username);
})
.catch((error) => {
// Some error occurred.
console.log('some error');
res.end('Error');
});
}
})
.catch((error) => {
res.end(JSON.stringify('UserNotFound'));
})
});
router.post('/login', (req, res) => {
const useremail = req.body.email;
const pass = req.body.password;
var username = ''
var admin = require("firebase-admin");
var serviceAccount = require("../xxxxxxsales-19e4e-firebase-xxxxxx-xxxxx-xxxxxxxx-xxxxxx.json");
if (!admin.apps.length) {
admin.initializeApp({
credential: admin.credential.cert(serviceAccount)
});
}
getAuth()
.getUserByEmail(useremail)
.then((userRecord) => {
// See the UserRecord reference doc for the contents of userRecord.
//console.log(`Successfully fetched user data: ${JSON.stringify(userRecord)}`);
if (userRecord.emailVerified) {
res.end(JSON.stringify(userRecord.displayName));
} else {
res.end(JSON.stringify('Pending'));
}
})
.catch((error) => {
// Some error occurred.
//console.log('some error');
res.end('Error');
});
});
const send_mail=(link,email,username) =>{
let { text } = 'Welcome'
const nodemailer = require('nodemailer');
let transport = nodemailer.createTransport({
service: 'gmail',
host: 'smtp.gmail.com',
port: 2525,
// secure: true,
auth: {
user: "xxxxxxxx.xx",
pass: "xxxxxxxxxxxxxxx"
},
debug: true,
logger: true
});
let mailTransporter = nodemailer.createTransport(transport);
transport.sendMail({
from: process.env.MAIL_FROM,
to: email,
subject: "Email verification",
ContentType: "multipart/alternative",
ContentType: 'text/plain', charset:"UTF-8", format:'flowed', delsp:'yes',
ContentTransferEncoding: 'base64',
html: `MY HTML CODE HERE `
});
}
router.get('/send_mail',cors(), (req, res) => {
let { text } = 'Welcome'
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
}
})
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>
`
})
})
module.exports = router;
My Front end(React):
if (form.email !== '' && typeof(form.email) !== undefined
&& form.password !== '' && typeof(form.password) !== undefined && errMessage === "") {
//props.saveLogin(form);
const databody =
form.password+" "+form.email+" "+form.fname;
// const data = await fetch('https://xxxxxxx-xxxxxx.el.r.xxxxxxx.com/signup/'+databody,
// {
// method: "POST",
// mode:'no-cors',
// headers:{headers}
// }
console.log('data Y1:'+ databody);
const data = await fetch('https://xxxxxxxxx-xxxxxx.el.r.xxxxx.com/signup/'+databody,
{
method: "POST",
mode: 'cors',
headers: {
"Accept": "application/json",
"Content-Type": "application/json"
}
}
).then((response) => {
console.log(response);
if (!response.status) {
//console.log("complete");
return response.json();
}
else {
throw new Error('Something went wrong');
}
})
.then((responseJson) => {
const items = responseJson.message;
//console.log(items);
//console.log("error new");
if (items==='Pending') {
alert('Email id already exist. Kindly check your inbox and verify.');
}
else if (items==='Registered') {
//alert('Email id registered successfully. Kindly check your inbox and verify.');
//alertA.show('Email id registered successfully. Kindly check your inbox and verify.');
CreateUser();
}
else if (items==='DBissue') {
alert('Db issue. Please try after sometime.');
}
else if (items==='Error') {
alert('Error. Please try after sometime.');
} else if (items==='Exist')
{
//console.log(items);
alert('Email is already registered. You may proceed to Login.');
}
else
{
alert('Error occurred. Please after sometime.')
}
})
.catch((error) => {
alert(error);
});
}
else if(errMessage !== ""){
console.log('in errMessage block');
alert(errMessage);
}