Search code examples
angularamazon-web-servicesaws-lambdaangular-httpclient

Invoke AWS Lambda function from within an Angular application using HTTP


I have made, build and deployed an AWS Lambda successfully using the AWS SDK for Java. I have tested the Lambda using the AWS console, no problems whatsoever.

Now I wish to invoke the Lambda function whenever someone clicks a button from within my Angular application. My first idea was to simply make an HTTP POST call to the Lambda API endpoint with a body.

See my following Service code:

export class Service{
    constructor(private httpClient: HttpClient) {}

    createContact() {
        const header: HttpHeaders = new HttpHeaders();
        header.append('Accept', 'application/text');

        this.httpClient
            .post(RELAY_URL, test, { headers: header, responseType: "text" })
            .subscribe((data) => {
                console.log(data);
            });
    }
}

Executing this method will in fact invoke the Lambda method and the lambda will successfully complete. However, my Angular client does not receive a proper response. This is what does happen, however:

  • I get an error regarding CORS in the browser console
  • I get an error regarding a failed Http Request in the console
  • In the networks tab of the developer windows of the browser I get a successful response from the Http request

I'm at a loss, and hope you can help.


Solution

  • CORS only protects you from reading the response in the browser:

    1. the request will fire
    2. server will execute
    3. the response will arrive , but
    4. the browser will not show you the result

    If you fire it from a prompt, you will get a response.

    I think you have to apply the domain you are calling from on the serverside (there should be a way to do this for an AWS lambda).

    This is just how CORS works.