Tips for sending data to a server in an object format using the POST method

Could someone kindly assist me? I am attempting to post user data in an object format, but it is not submitting in the desired way. Please, can someone help as I do not want it to create a new object. Here is how I would like it to be submitted:

{"birthdate":"1998","email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0f65604f65606a216c6062">[email protected]</a>","firstname":"jo","lastname":"david","phone":"012345678","sex":"male","identifier":"32323232","username":"joe","password":"Kdsdsdsddew32","country":"sa","affiliate":"3232"}

However, it is submitting like this:

{"user":{"birthdate":"1998","email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0f65604f65606a216c6062">[email protected]</a>","firstname":"jo","lastname":"david","phone":"012345678","sex":"male","identifier":"32323232","username":"joe","password":"Kdsdsdsddew32","country":"sa","affiliate":"3232"}}

Below is my code:

 constructor(private http: Http, private htp: HttpClient) {

let user = {
  birthdate: '',
  email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="610b0e210b0e044f020e0c">[email protected]</a>',
  firstname: 'jo',
  lastname: 'david',
  phone: '012345678',
  sex: 'male',
  identifier: '43425',
  username: 'joe',
  password: 'Kdsdsdsddew32',
  country: 'sa',
  affiliate: '3232'
};


const headers = new HttpHeaders({'Content-Type':'application/json; charset=utf-8'});

const params = new FormData();
// params.append('token', authResult.idToken);
params.append('', JSON.stringify(user));

this.htp.post(' http://192.168.66:323/test',  {user}, {headers}).
subscribe(data => {
  this.data = JSON.stringify(data);
});

}

Answer №1

In Angular, JSON conversions are handled automatically. By passing the object variable to the POST method and receiving JSON data with the correct headers from the server, Angular will parse the response and return a JavaScript object (similar to using JSON.parse).

sendData(data) {
  const httpOptions = {
    headers: new HttpHeaders({
      'Content-Type':  'application/json'
    })
  };

  return this.http.post("https://example.com/api", data, httpOptions);
}

Elsewhere in your code...

const user = {
  name: "John"
}
dataService.sendData(user)
  .subscribe(response => {
    ...
  });

The reason for getting user: {...} encapsulation is due to this line of code:

this.htp.post(' http://192.168.66:323/test',  {user}, {headers}).

By creating a new object and assigning the key user within this object as the variable you defined with let user = {,

This is a shorthand in Javascript, equivalent to

this.http.post("...", { user: user }, { headers: headers })
. No need to create new objects, simply pass the original object.

Answer №2

To include, simply enter:

this.http.send(' http://192.168.66:323/test', data, {headers})

Omit the brackets as it is currently in object form.

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

You are only able to click the button once per day

I am working on a button that contains numeric values and updates a total number displayed on the page when clicked. I would like this button to only be clickable once per day, so that users cannot click it multiple times within a 24 hour period. Below i ...

Explaining the concept of SwitchMap in RxJS

Currently, I am utilizing Restangular within my Angular 5 project. Within the addErrorInterceptor section, there is a code snippet that invokes the refreshAccesstoken method and then retrieves the new access token in the switchMap segment. My approach invo ...

Exploring node.js: How to extract elements from a path

I have an array of individuals as shown below: individuals = ['personA', 'personB', 'personC']; I am looking to create a dynamic way to showcase each individual's page based on the URL. For instance, localhost:3000/indi ...

What are effective solutions to reduce the increasing Next.js bundle size caused by dynamic component lookup?

tldr: For more information, please visit the repository. The common.js file includes all dependencies, even though only one is used on the current page. http://localhost:3000/components/ComponentOne http://localhost:3000/components/ComponentTwo Live dem ...

Using the input type 'number' will result in null values instead of characters

My goal is to validate a number input field using Angular2: <input type="number" class="form-control" name="foo" id="foo" [min]="0" [max]="42" [(ngModel)]="foo" formControlName="foo"> In Chrome, everything works perfectly because it ignores ...

What methods can be used to cloak JavaScript functions from the end user?

Looking to utilize jQuery AJAX calls? Here's an example: function addNewTeacher(){ $.ajax({ type: "POST", url: "/actions/dboss/newteacher.php", data: "uname=" + $("#newteacheruname").val() + "&upass=" + $("#new ...

updating Chart.js to dynamically draw a line chart with updated dataset

Is there a way to pass back the retrieved value into the dataset data without it returning empty? It seems that the var durationChartData is empty because the array is initialized that way. How can I update it to display the correct values after receiving ...

Change the color of the plotly button when it is clicked

I recently implemented a custom button on my plotly modeBar and I would like it to retain a distinct color when clicked. This would help visually indicate its "active" state, allowing users to easily discern whether it is enabled or disabled based on its ...

Troubleshooting a Custom Pipe Problem in Angular Material Drag and Drop

Currently, I am working on a project involving Angular Material Drag And Drop functionality. I have created a simplified example on StackBlitz which you can access through this link: here The project involves two lists - one containing pets and the other ...

Having trouble uploading SharePoint list item with attachment from Angular to ASP.NET Core Web API via NgModel

Recently, I successfully added a SharePoint list item with an attachment from Angular to ASP.NET Core Web API. This was achieved using FormControl in the Angular application. I found guidance on how to upload files from Angular to ASP.NET Core Web API at ...

Angular 2 project experiencing issues with implementing Bootstrap styles

After adding Bootstrap CSS to angular-cli.json - styles, I noticed that the styles were not being applied to my project. I also added it in package.json and did an npm install. Can anyone suggest a solution? Here is a snippet from angular-cli.json: ...

What steps should I take to resolve the error: Uncaught SyntaxError: expected expression, received '<'?

I'm facing an issue with my code. It works perfectly on my computer, but when I move it to the server, I encounter the following error. Error: Uncaught SyntaxError: expected expression, got '<' Here is the code snippet causing the prob ...

Guide to personalizing NbLayoutComponent through the creation of a new class extension

Is there a way to make the footer full screen width instead of just the contents section in my app? I am using Nebular for building it. I have tried creating a custom component by extending nbLayoutComponent, but I'm not sure if this is the correct a ...

Issue TS1259: The module "".../node_modules/@types/bn.js/index"" can only be imported as the default using the 'esModuleInterop' flag

Currently, I am utilizing Hiro Stack.js which I obtained from the following link: https://github.com/hirosystems/stacks.js/tree/master/packages/transaction. For additional information, please refer to . Even when attempting to compile a fully commented out ...

Establishing a PHP session variable and then initiating a redirect to a new page through the HREF method

I am working on a table that pulls IDs from a MySQL table named auctiontable and displays them in rows. Currently, I can easily append ?aid="1"or ?aid="2" to the end of the href attribute to utilize $_GET. However, I want to prevent users from controllin ...

The THREE.js WebGLRenderer canvas captures the 'click' mouse event

After including the domElement (canvas) from THREE.js WebGLRenderer in my document, I noticed that the 'click' mouse event no longer triggers when clicking on the container element containing the canvas. Is there a method to prevent the canvas f ...

Application of Criteria for Zod Depending on Data Stored in Array Field

I am currently working on an Express route that requires validation of the request body using Zod. The challenge arises when I need to conditionally require certain fields based on the values in the "channels" field, which is an array of enums. While my cu ...

What is the method for getting js_xlsx to include all empty headers while saving the file?

In the midst of developing a Meteor App, I've incorporated the Node.js package known as "js_xlsx" from "SheetJS", produced by "SheetJSDev". This tool enables me to convert an Excel sheet uploaded into JSON on the backend. The intention is to store thi ...

Error in ReactJS: Trying to access property 'items' of an undefined object

I've been diving into ReactJS, but I've hit a roadblock with this perplexing error. My goal is to update the parent's items array state from its child component. To achieve this, I attempted to pass the addItem function as a prop to the chi ...

What is the best way to retrieve the parent of the initial jQuery object?

At the bottom of a lengthy table containing multiple button.enter-match elements, I am using the following code: $("button.enter-match") .button() .on('click', function() { $("form.enter-match").dialog({ modal: true, height: ...