![](/img/trans.png)
[英]Why do I get a CORS internal server error when trying to do a DELETE request via AWS API Gateway and Lambda?
[英]Why do I get a CORS error on API Gateway GET request when the OPTIONS request has statusCode 200?
我正在嘗試向連接到lambda函數的AWS API Gateway端點發出GET HTTP請求。
與postman測試時,端點和lambda函數照常工作,這是合乎邏輯的,因為postman不使用CORS。
但是,在chrome上使用Firefox進行測試時,出現以下錯誤:
火狐:
跨域請求被阻止:同源策略禁止讀取[ url ]處的遠程資源(原因:缺少CORS標頭'Access-Control-Allow-Origin')。
鉻:
從源“ http:// localhost:8080 ”獲取[ url ]的訪問已被CORS策略阻止:請求的資源上沒有“ Access-Control-Allow-Origin”標頭。 如果不透明的響應滿足您的需求,請將請求的模式設置為“ no-cors”,以在禁用CORS的情況下獲取資源。
但是,如果我查看CORS Preflight請求的響應,就會發現存在“ Access-Control-Allow-Origin”:
HTTP / 2.0 200 OK
日期:周二,2019年3月12日15:22:57 GMT
內容類型:application / json
內容長度:0
x-amzn-requestid:[x-amzn-requestid]
訪問控制允許來源:*
訪問控制允許標題:Content-Type,X-Amz-Date,授權,X-Api-Key,X-Amz-Security-Token
x-amz-apigw-id:[x-amz-apigw-id]
訪問控制允許方法:GET,OPTIONS
X-Firefox-Spdy:h2
我嘗試使用以下代碼對請求同時使用fetch和request包(我將請求調用包裝在Promise中,以使用async-await流,如fetch調用):
const getPolicy = (baseUrl, bucketNameTranscribe, fileName, apiKey) => (
new Promise((resolve, reject) => {
request({
url: `${baseUrl}?bucketName=${bucketNameTranscribe}&key=${fileName}`,
method: "GET",
headers: {
"x-api-key": apiKey
}
}, ((error, response) => {
if (error) {
reject(error);
} else if (response.statusCode === 200) {
resolve(JSON.parse(response.body));
} else {
reject(response);
}
});
})
);
const upload = async() {
const {
policyUrl,
bucketNameTranscribe,
apiKey
} = awsConfig;
const fileName = `${Date.now()}.mp3`;
const req = new Request(
`${policyUrl}?bucketName=${bucketNameTranscribe}&key=${fileName}`,
{
method: "GET",
headers: new Headers({
"x-api-key": apiKey
})
}
);
try {
const response1 = await fetch(req);
console.log("fetch", response1);
} catch (error) {
console.error("errorFetch", error);
}
try {
const response2 = await getPolicy(policyUrl, bucketNameTranscribe, fileName, apiKey);
console.log("request", response2);
} catch (exp) {
console.error("errorRequest", exp);
}
}
在此先感謝您的幫助
錯誤消息顯示:
所請求的資源上沒有'Access-Control-Allow-Origin'標頭。
實際資源中缺少Access-Control-Allow-Origin
標頭,而不是對預檢OPTIONS請求的響應。
它必須同時存在 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.