我有一个react front应用,该应用基于lambda和express调用rest api。集成是通过AWS API Gateway完成的。即使使用cors模块也无法实现我想要的功能。
这是代码:
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;
我不断收到此消息:
从原点“ ...”获取“ ...”处的访问已被CORS策略阻止:请求的资源上不存在“ Access-Control-Allow-Origin”标头。如果不透明的响应可以满足您的需求,请将请求的模式设置为“ no-cors”,以在禁用CORS的情况下获取资源。