Sending a POST request with parameters using HttpClient

My current challenge involves making a POST request to an endpoint that requires query string parameters instead of passing them in the body of the request.

const params = new HttpParams()
  .set('param1', '1')
  .set('param2', '2');

const url = environment.apiUrl + 'Service/Endpoint';

return this
  .httpClient
  .post<ServiceResponse>(url, { params })
  .pipe(map(res => res.httpStatusCodeSuccess));

Despite my efforts, I continue to receive a 404 error because the call does not contain any query string parameters. This was confirmed by analyzing the network activity.

Interestingly, the same code works perfectly for GET requests when using .get(), but encounters issues with .post() against a POST endpoint. What could be the missing piece in this puzzle?

Answer №1

When using the Angular post method, the second parameter represents the http body to be included in the request. If no body is needed, simply pass null as the argument and then provide any params as the third argument.

.post<ServiceResponse>(url, null, { params: params })

The reason for this distinction is that in a HTTP GET call, you cannot include a body like you can with a POST call.

Answer №2

One possible explanation is that the issue arises from passing the parameters as an object.

Take a look at the example provided below

const myheader = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded')

let body = new HttpParams();

body = body.set('username', USERNAME);
body = body.set('password', PASSWORD);

http.post('/api', body, {
    headers: myheader),
})

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

Executing a particular end-to-end test case using Angular 2, Karma, and Protractor

Is there a specific command I can use to run an individual e2e test case from my test suite? If that's not possible, is there some workaround for running a specific test suite? I'm currently using Jasmine, Karma, and Protractor. To start my tes ...

Exploring the concept of kleisli composition in TypeScript by combining Promise monad with functional programming techniques using fp-ts

Is there a way to combine two kleisli arrows (functions) f: A -> Promise B and g: B -> Promise C into h: A -> Promise C using the library fp-ts? Having experience with Haskell, I would formulate it as: How can I achieve the equivalent of the > ...

The data from Angular2 Observable Subscription appears undefined, although a closer look at the Browser Debug reveals otherwise

Is it possible there is an issue with the data subscription process? Upon subscribing to data from a service call, 'undefined' is returned as the data set. Surprisingly, when I debug the code in the browser, it clearly shows that the correct dat ...

React Bootstrap Forms: The <Form.Control.Feedback> element is failing to display when the validation is set to false

Problem: I am facing difficulties with displaying the React Bootstrap <Form.Control.Feedback></Form.Control.Feedback> when the validation is false in my form implementation. Steps to Recreate: Upon clicking the Send Verification Code button, ...

Understanding Scope in TypeScript

Recently, I developed a sample application in Node.js which utilizes pg-promise to execute queries on a Postgres database. I encapsulated this functionality within a class named PostgresDataAccess. However, I encountered an issue while trying to access t ...

My component reference seems to have gone missing in angular2

Trying to load my Angular 2 app, I encountered this error: https://i.stack.imgur.com/FmgZE.png Despite having all the necessary files in place. https://i.stack.imgur.com/kj9cP.png Any suggestions on how to resolve this issue? Here is a snippet from ap ...

Exploring the Pristine State of Nested Controls in Angular Reactive Forms

I'm currently in the process of putting together a nested form that's relatively simple. Form Group > Form Array > Form Group > Controls Within the HTML, I am attempting to include a Remove button that will only display when the last i ...

Ways to limit the combination of general types in Typescript?

Struggling to develop a React form component with generic types. The initialValues parameter determines the generic type for the form. Unable to figure out how to specify the type for each field in Typescript. Check out my CodeSandbox where I've at ...

Angular form: Choose an option by selecting it and clicking on a button

I need help with my Angular form. I want to allow users to select a value when they click on a button. How can I achieve this? page.html <div *ngFor="let product of products; index as i"> <button (click)="chooseProduct(i)">{{product.name} ...

Angular 8 wild card redirect problem with Routable Modals

I have a Modal that can be routed with unique parameters to display Training content defined in the app-routing.module.ts file { path : 'TopshelfContent/:catName/:cmsID', component: ModalContainerComponent, canActivate: [MsalGuard]}, When manua ...

What mechanism allows Angular 2 to identify the parent instance without the need for explicit coding?

Can anyone provide some insight for me please? I have been following this example to create a simple wizard app in Angular 2. Everything is working smoothly, but what confuses me is the constructor in the file called my-wizard-step.ts. How does the private ...

Using Math.min() or Math.max() syntax in Angular templates: A comprehensive guide

Within my pagination module, the following code snippet can be found: <p>Displaying {{(page-1) * pageSize}} to {{ Math.min((page-1) * pageSize + pageSize,tasks.length)}} out of {{tasks.length}}</p>. Unfortunately, it seems to be experiencing ...

Having difficulties fetching token from response header in Angular 6 connected to a backend using Spring

In my development environment, I am using Angular 6.0.9 with Spring Boot 2.0.7 and Spring 5.0.7. I have encountered a frustrating issue where my Angular application is unable to detect the token present in the request header. On the backend, I am using Sp ...

Patterns for Spring Boot backend and Angular frontend designor Strategies for designing a Spring

I have developed an application that utilizes Spring Boot for its back end and Angular for the front end, connected through APIs. The Spring Boot components include: Dao Controller Entity Service and other classes. Upon studying further, it appears that ...

Retrieving desired route in Angular 2 RC5 within canDeactivate function

Is there a way to retrieve the desired route within the CanDeactivate guard of the Angular 2 RC5 router? I came across a solution for a similar scenario involving CanActivate (CanActivate), but it doesn't seem to apply to CanDeactivate. My specific s ...

The Angular Tooltip feature is unable to interpret the characters "' '" or "' '"

Let me explain the scenario: I am receiving a list of objects from my back-end service, which I then break apart using ngFor and display accordingly. Each item in the list has an associated toolTip that provides additional information. The info for each i ...

Issue with the declaration of custom types in Typescript

I've created a type declaration for r-dom as shown below: /// <reference types="react" /> declare module 'r-dom' { interface IRDOMFacade extends React.ReactDOM { (component: React.Component<any, any>, properties?: ...

I have an Observable but I need to convert it into a String

Seeking assistance with Angular translation service and Kendo.UI components. In the Kendo.UI documentation, it mentions the use of MessageService for component translation implementation. To achieve this, an abstract class must be extended containing a m ...

Tips for eliminating the undefined/null values from an array nested within another array in Angular

DATA = [{ application: [{ name: 'Room1' },{ name: 'Room2' },{ name: 'Room3' },{ name: 'Room4' },{ name: 'Room5' }], name: 'Batch 1&ap ...

Using Angular 5+ to fetch information from an ASP.NET Core Web API

Having trouble retrieving data from an ASP.NET Core 2.0 Web API with Angular 5+. The steps taken so far are as follows: An ASP.NET Core 2.0 Web API was created and deployed on a server. Data can be successfully retrieved using Postman or Swagger. Using ...