I have a react front app which invokes rest api based on lambda and express. The integration is done via AWS API Gateway. Even the with the cors module I do not achieve what I want.
This is the code:
const express = require('express');
const app = express();
require('dotenv').config();
const youTube = require('./lib/youtube');
const ffmpeg = require('fluent-ffmpeg');
const Logger = require('./lib/logger');
const cors = require('cors');
const serverLogger = new Logger(__filename);
// Init Middleware
app.use(express.json({ extended: true }));
app.use(cors({ origin: true }));
app.get('/', (req, res) => {
res.json({ msg: 'Welcome to the YouTube downloader API...' });
});
app.post('/api/youtube/download', async (req, res) => {
const body = req.body;
const { url } = body;
res.header('Content-disposition', 'attachment; filename=video.mp3');
res.header('Access-Control-Allow-Headers', 'Content-Type');
res.header('Access-Control-Allow-Methods', 'OPTIONS,POST,GET');
res.header('Access-Control-Allow-Origin', '*');
const youTubeStream = await youTube.getStream(url);
ffmpeg(youTubeStream)
.format('mp3')
.audioBitrate('192k')
.on('end', function () {
console.log('file has been converted succesfully');
res.status(200);
})
.on('error', function (err) {
console.log('an error happened: ' + err.message);
res.status(500).json({ error: err.message });
})
// save to stream
.pipe(res, { end: true });
});
app.post('/api/youtube/info', async (req, res) => {
const body = req.body;
console.log(body);
const { url } = body;
const title = await youTube.getInfo(url);
console.log(title);
res.status(200).json({ title: title });
});
module.exports = app;
I keep on getting this message:
Access to fetch at '...' from origin '...' has been blocked by CORS policy: 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.