I have a frontend application built with Angular and TypeScript where I need to make an HTTP request to an AWS API Gateway. The challenge is converting the existing JavaScript code into TypeScript and successfully sending the HTTP request.
The AWS API gateway requires an AWS Cognito jwtToken (referred to as "accessToken"), a specific "type" parameter indicating the function to execute on the API (in this case 'POST'), and a data selection string.
Auth.currentSession().then(token => {
const accessToken = token.getIdToken().getJwtToken();
console.log('from floorview: ' + accessToken);
function requestItem(source) {
$.ajax({
type: 'POST',
url: 'https://XXXXXXXXXX.execute-api.eu-central-1.amazonaws.com/prop/dashboard',
headers: {
Authorization: accessToken
},
data: JSON.stringify({
Source: source.toString(),
tableName: 'h16b-testset',
operation: 'read'
}),
dataType: 'json',
contentType: 'application/json',
success: completeRequest,
error: function ajaxError(jqXHR, textStatus, errorThrown) {
console.error('Error requesting ride: ', textStatus, ', Details: ', errorThrown);
console.error('Response: ', jqXHR.responseText);
alert('An error occured when requesting your unicorn:\n' + jqXHR.responseText);
}
}).then(response => console.log(response));
}
requestItem(996);
function completeRequest(result) {
console.log('Response received from API: ', result);
}
});
}
The main issue now is how to convert this JavaScript code into TypeScript while utilizing Angular's HTTPClient for the HTTP request. If there is a different approach that can be recommended, please advise me. Whenever I attempt to run this code using HTTPClient, I consistently receive 401 or 403 errors.
Auth.currentSession().then(token => {
const accessToken = token.getAccessToken();
const jwtToken = accessToken.getJwtToken();
this.authKey = jwtToken;
const params = new HttpParams().set('Source', '996');
params.append('tableName', 'h16b-testset');
params.append('operation', 'read');
const headers = new HttpHeaders().set('Authorization', this.authKey);
headers.append('content-type', 'application/json');
this.http.request(
'POST',
'https://XXXXXXXX.execute-api.eu-central-1.amazonaws.com/prop/dashboard',
{
headers,
responseType: 'json'
}
).subscribe(
response => {
console.log('hello' + response);
},
error => {
console.log('error occurred with HttpClient: ' + error.message);
}
);
});