我正在使用 AWS API Gateway 并使用 Angular 2 代码调用我的 API,问题是当 session token 过期并且我的 UI 代码尝试使用它时 - API 网关抛出 403 错误,指出“安全 token 包含在请求中已过期”..这是我在控制台中看到的 - 网络部分。
现在这个 403 错误在 Promise 代码中被捕获 => 捕获处理程序,我尝试显示服务器发送的消息,即
{"message":"The security token included in the request is expired"}
这是问题所在 - 我无法在控制台和 Sweet Alert Box 中显示正确的错误消息。
在调试 Catch 处理程序接收到的错误对象时,会显示此 Json - 实际错误对象不存在的地方。
{"data":"","status":0,"statusText":"","headers":{},"config":{"method":"GET","headers":{"x-api-key":"<api-key>","Accept":"application/json","x-amz-date":"201705957Z","Authorization":"AWS4-HM256 Credential=ASIAJ66A/20170317/us-west-1/execute-api/aws4_request, SignedHeaders=accept;host;x-amz-date;x-api-key, Signature=59a2bce53fc3fc25a0dcc36c80243ae63","x-amz-security-token":"<security-token>","Content-Type":"application/json"},"timeout":0,"transformRequest":[null],"transformResponse":[null],"url":"https://api.tech.in/adviser/Suraj","data":""}}
我能够解决 API 网关在提供错误的密码或用户名时发送的 400 错误。
注意:CORS 已启用且映射响应和集成有 403 错误映射错误显示 header 有 CORS。
该怎么做 - 解决这个问题 - 因为在 catch 处理程序中捕获的最终错误对象没有正确的 http 响应数据
这是我的代码
// this is the final Consumer of the Promise
this.http.getFundDetailedList() //***
.then(response => this.fundDetailsList = response.data.Items)
.catch(err => {
swal('Error Reported', "Please login again \n"+err.data, 'error');
console.log(this.handleError(err));
});
}
// helper function for Error Handling
private handleError(error: Response | any) {
let errMsg: string;
console.log('Error Json '+ JSON.stringify(error)); // Wrong Error Object shown in console
if (error instanceof Response) {
const body = error.json() || '';
const err = body.error || JSON.stringify(body);
errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
} else {
errMsg = error.message ? error.message : JSON.stringify(error.data.message);
}
return errMsg;
}
// Calls AWS API - coded inside a http service class
getFundDetailedList() {
return this.credentialService.getAwsSDK().adviserFundsGet({ 'adviser': this.credentialService.$id }, {}, {});
}
最佳答案
对于 API 网关中的身份验证失败,CORS header 未正确发送。这是一个已知问题,您可以在 aws 论坛上找到更多详细信息
https://forums.aws.amazon.com/thread.jspa?messageID=671237򰀷
本质上,对于某些类型的错误(身份验证失败/错误请求/api key 身份验证/问题调用集成), header 映射将被跳过,这意味着 CORS header 不会在响应中返回。
对于给您带来的不便,我们深表歉意。但我们正在积极努力解决这个问题。
关于javascript - 无法获得映射到 Angular 2 代码中的正确 http 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42858647/