首页 > 解决方案 > Lambda (node) Express REST API with AWS API Gateway 502 Bad Gateway 错误

问题描述

我有一个反应前端应用程序,它调用基于 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 的资源。

标签: node.jsamazon-web-servicesaws-lambdaaws-api-gateway

解决方案


推荐阅读