node.js - 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 的资源。
解决方案
推荐阅读
- amazon-web-services - 使用 AWS lambda 在 Athena 上运行查询
- git - 哪个 Jenkins 命令获取已更改文件的列表
- python - 尝试使用 tweepy 调用 Twitter API 时超过最大重试次数
- c# - 如何使用 Web API JWT 令牌验证 MVC 用户登录表单?
- android - 位置 Android 8.0 以上的前台服务
- python - 寻找一种用随机数填充列表的方法(基于用户输入的数字量)
- java - dataSnapshot 自动更新时如何禁用按钮?
- java - Google Admin SDK - 使用 Java 客户端 API 将组添加到另一个组
- ruby-on-rails - Production.rb 未在生产环境中读取环境变量
- istio - 我可以在不启用 mtls 的情况下运行 istio 吗?