【发布时间】:2020-09-02 21:23:28
【问题描述】:
const https = require('https');
export async function main(event, callback) {
const options = {
method: 'GET',
host: 'https://api.challonge.com/v1/',
headers: {
'Access-Control-Allow-Methods': 'GET',
"api_key": "THE_KEY",
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Credentials": true
}
};
var dataString = " ";
const response = await new Promise((resolve, reject) => {
const req = https.get(options, function (response) {
response.on('data', chunk => {
dataString += chunk;
});
response.on('end', () => {
resolve({
statusCode: 200,
headers: {
"Access-Control-Allow-Origin": "*"
},
body: JSON.stringify((dataString))
});
});
});
req.on('error', (e) => {
reject({
statusCode: 500,
headers: {
"Access-Control-Allow-Origin": "*"
},
body: e.message
});
});
});
return response;
};
这是 lambda 函数 ^
getChallongeTournaments:
handler: getChallongeTournaments.main
events:
- http:
path: tournaments/
method: get
cors: true
authorizer: aws_iam
我的 serverless.yml
// in a useEffect
function getChallongeTournaments(){
return API.get("byoc_users", '/tournaments.json');
}
async function onLoaded() {
try {
const testChallonge = await getChallongeTournaments();
^ API 调用
根据 challonge 文档,这应该会收到“检索使用您的帐户创建的一组锦标赛”。并且创建了一个。
这是我收到的 CORS 错误:从源“http://localhost:8100”访问 XMLHttpRequest 在“https://m3heucf413.execute-api.us-east-2.amazonaws.com/prod/tournaments.json”已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:确实如此没有 HTTP ok 状态。
【问题讨论】:
-
Access-control-allow-credentials 可能不会像您认为的那样做,并且会施加奇怪的规则。最常见的错误是 lambda 爆炸从 API 网关服务返回 500 而没有 cors
标签: reactjs amazon-web-services api aws-lambda serverless