this is my first post on Stack Overflow. I’ve recently been working on an online invoice generator using the MERN Stack with TypeScript. I have included an option to generate a PDF using the Puppeteer library when a button is clicked. This feature works fine on my local device. I have deployed the backend of this project on Render and the frontend on Vercel. However, when I click on the button to generate the PDF on the deployed page, the following error appears:
‘Access to XMLHttpRequest at ‘https://invoice-generator-1-yyv7.onrender.com/api/v1/generate-pdf’ from origin ‘https://invoice-ninja-aryan.vercel.app’ has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.’
This is my cors: –
app.use(
cors({
origin: “*”,
credentials: true,
methods: [‘GET’, ‘POST’, ‘PUT’, ‘DELETE’, ‘OPTIONS’]
})
);
Below is the backend function implementing the generatePDF Function
app.post(‘/api/v1/generate-pdf’, auth, async (req, res) => {
const { user, products} = req.body;
let totalRate = 0;
const processedProducts = products.map(product => {
const total = product.quantity * product.price;
totalRate += total;
return {
...product,
total: total
};
});
// Calculate total GST and grand total
const totalGST = totalRate * 0.18; // Assuming GST rate is 18%
const grandTotal = totalRate + totalGST;
// Load HTML template
const templatePath = path.join(__dirname, 'invoiceTemplate.html');
const templateHtml = fs.readFileSync(templatePath, 'utf8');
// Compile template with Handlebars
const template = Handlebars.compile(templateHtml);
const html = template({
userName: user.name,
userEmail: user.email,
products: processedProducts,
totalRate: totalRate,
totalGST: totalGST,
grandTotal: grandTotal
});
// Launch Puppeteer and generate PDF
const browser = await puppeteer.launch({
headless: true,
devtools: true,
args: [
'--disable-web-security',
'--disable-features=IsolateOrigins',
'--disable-site-isolation-trials',
'--disable-features=BlockInsecurePrivateNetworkRequests'
]
});
const page = await browser.newPage();
await page.setContent(html);
const pdfBuffer = await page.pdf({
path: 'mypdf.pdf',
format: 'A4',
printBackground: true,
});
await browser.close();
// Send PDF as response
res.set({
'Content-Type': 'application/pdf',
'Content-Length': pdfBuffer.length
});
res.send(pdfBuffer);
});
I tried the methods posted by others on stack overflow but none of the approaches worked for me. Please help me out !!
I attempted the methods suggested by others on Stack Overflow, but none of them worked for me. Can someone please assist me?
WTF itz Aryan is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.