How to mimic CURL Post using Angular HttpClient

Discussão em 'Angular' iniciado por Darren Gates, Fevereiro 9, 2025.

  1. Darren Gates

    Darren Gates Guest

    I have some Angular code using HttpClient, and I simply want to use the "post" method, with a particular payload and headers, with the "toPromise()" option. Yes, I realize toPromise() is deprecated, but I need to use it anyway.

    In the class below, which does NOT actually run but is a representative sample of what my real project looks like, you'll observe a CURL console.log. When I copy the logged CURL and run it in my Mac terminal, it runs perfectly and yields a correct result from the server.

    However, when I run the await this.http.post, I get an error like "Error response is not a String". I assume at this point that the issue is with how I am constructing the HttpClient object, since I know (because of the CURL) that the server API endpoint is fine.

    import { HttpClient, HttpHeaders } from '@angular/common/http';

    class CheckoutComponent {
    constructor(private http: HttpClient) {}

    async testCheckout() {
    const payload = {
    "amount": 12,
    "user_id": "12345",
    "token": "the_token"
    };

    const headers = {
    headers : new HttpHeaders({
    'Content-Type': 'application/json'
    }),
    responseType: 'text' as 'json'
    }

    const url = 'https://path/to/api/endpoint'

    const curlCommand = `curl -X POST -H "Content-Type: application/json" -d '${JSON.stringify(payload)}' ${url}`;

    // this command works when I run it in the terminal
    console.log(curlCommand);

    // THIS PRODUCES AN ERROR
    // QUESTION: How do I mimic the above CURL Request using HttpClient?
    await this.http.post(url, payload, headers).toPromise();
    }
    }

    Continue reading...

Compartilhe esta Página