Using an AWS API Gateway, an HTTP client sends a request to access resources

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);
        }
      );
    });

Answer №1

Revamp your http client like so:

    this.http.post(
          'https://XXXXXXXX.execute-api.eu-central-1.amazonaws.com/prop/dashboard',
          {
            Source: '<id>',
            tableName: 'h16b-testset',
            operation: 'read'
          },
          {
              headers: new HttpHeaders({'Content-type': 'application/json', 'Authorization': '<token>'})
          }
    ).subscribe(res=> console.log(res), failure => console.error(failure))

This approach ensures the source is sent in the body of the request along with the authorization token in the header.

To learn more about HttpClient, visit https://angular.io/guide/http.

Answer №2

If you want to implement a similar functionality, consider the following example that utilizes the concatMap operator:


import { from } from 'rxjs';
import { concatMap } from 'rxjs/operators';

export class AuthorizationService {

  constructor(private http: HttpClient) {
    from(Authorization.currentSession())
    .pipe(concatMap(token => this.fetchData(token, 996)))
    .subscribe(
        result => console.log('Received response from API: ', result),
        err => {
          console.log('An error occurred with HttpClient: ' + err.message);
        }
     );
  }

  fetchData(token, source): Observable<any> {
    this.http.post(url, {
            Source: source.toString(),
            tableName: 'h16b-testset',
            operation: 'read'
          }, 
         headers,
         params
    );
  }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Unable to modify border color for Material-UI OutlinedInput

Having some trouble changing the border color of a v4.13 MaterialUI Outlined Input. No luck with CSS overrides. Tested multiple CSS rules targeting different elements, such as select and OutlinedInput. Here are my latest attempts. What am I missing? cons ...

Press a button to generate an image inside a specified div element

I've been struggling with this particular issue and have attempted various solutions, but there seems to be an error in my implementation as it's not functioning correctly. My goal is simple: I want to be able to click a button and have an image ...

Steps for updating a text section beneath a carousel

I'm looking to enhance my webpage with a bootstrap carousel, which is pretty standard. However, I want the content under each slide to change dynamically, but I'm struggling to make it work. As a newbie, I could use some guidance. I've atte ...

What is the process for updating selenium-webdriver if it is not globally installed on my system?

After installing selenium-webdriver with the command npm install selenium-webdriver (without the -g option), I found that the usual instruction of running webdriver-manager update did not work since it was installed locally. What is the correct way to upd ...

The image will remain hidden until it is fully loaded and ready to be displayed

I am currently working on a script that involves displaying a loading icon until an image is fully loaded, at which point the loading icon should disappear and the image should be shown. Unfortunately, my current code is not working as intended. Here is a ...

Updating a Parent component from a Child component in React (Functional Components)

My functional component RoomManagement initiates the fetchRooms function on the first render, setting state variables with data from a database. I then pass setLoading and fetchRooms to a child component called RoomManagementModal. The issue arises when t ...

What is the best way to locate values within observable data fields?

let filteredRows$: Observable<any[]> = combineLatest([ this.items$, this.term$, ]).pipe( map(([items, term]) => items.filter( (item) => term === "" || item.product_name === term || ...

Searching for true values in MongoDB using the query syntax can be challenging

I have a question that might be a bit embarrassing, but I need help with rendering a user search based on both location and date. Our profile object is structured like this: availability: { monday: { type: Boolean, default: false }, tuesday: { type ...

Embedding content within various ng-template elements

I'm currently working on developing a button component (app-button) that can utilize multiple templates based on the parent component using it. <div class="ds-u-margin-left--1 ds-u-float--left"> <ng-container *ngTemplateOutlet="icon">< ...

What is the best way to merge the results of several runs of an observable function

When working with Firestore, I need to retrieve multiple documents, each with a unique sourceAddressValue. This means for a list of N strings, I may need to fetch N documents. I attempted the following approach: getLocationAddresses(addresses: string[]) { ...

Adjust the child element's value by referencing the parent class name

I need to update the content of child elements within an HTML file based on the class name of their parent element, using JavaScript. While I have successfully achieved this for static values by creating a TreeWalker for text nodes, doing the same for dyn ...

Troubleshooting JavaScript Integration in PHP Scripts

I'm currently working on creating an advertisement switcher that can display different ads based on whether the user is on mobile or desktop. I've tried inserting PHP includes directly into the code, and while it works fine, I'm struggling t ...

Personalize your Client-Id for Paypal

Currently integrating PayPal's Smart Payment Buttons into my Angular project. The index.html file contains the following script: <script src="https://www.paypal.com/sdk/js?client-id=MY_CLIENT_ID"> </script> I am working on developi ...

Expo running into issues with recognizing .jsx files when using Jest

I'm encountering an issue with running jest to execute its test suite on .jsx files within my Expo project. Here is my babel.config.js: module.exports = function (api) { api.cache(true); return { presets: ['babel-preset-expo'], }; ...

When selecting a different file after initially choosing one, the Javascript file upload event will return e.target as null

Currently, I have implemented file uploading using <input>. However, when attempting to change the file after already selecting one, the website crashes and states that event.target is null. <Button label="Upload S3 File"> <input ...

Vue.js SyntaxError: Identifier came out of nowhere

An error was reported by VUE debug mode in this line of my code: :style="{transform : 'translate3d(' + translateX + 'px,0, 0)'}"\ The documentation does not provide instructions on how to include a variable within a style binding ...

Having challenges retrieving information from MySQL in AngularJS

As a beginner in angularJS, I am trying to display all customers from MySQL. Here is the code I have written in the controller and service: app.controller('CustomersController', function ($scope, customersService, $http) { init(); function ini ...

The functionality of jQuery binding is not functioning properly

I've been playing around with jQuery and have a code snippet that includes: // buttons for modifying div styles by adding/removing classes <button class="size" id="switcher-large"> Large Print </button> <button class="size" id="switche ...

Switch out the ajax data in the input field

Is there a way to update the value in a text box using Ajax? Below is my code snippet: <input type="text" id="category_name" name="category_name" value="<?php if(isset($compName)) { echo ucfirst($compName); ...

Best practices for annotating component props that can receive either a Component or a string representing an HTML tag

What is the correct way to annotate component props that can accept either a Component or a string representing an HTML tag? For instance, imagine I have a component that can receive a custom Component (which includes HTML tags like div, p, etc.). The cod ...