The http post request is functioning properly in postman, but it is not working within the ionic app

I am currently developing an app in ionic v3 within visual studio (Tools for Apache Cordova). On one of the screens in my app, I gather user information and send it to an API. However, I'm encountering an issue with the HTTP POST request that I'm making - it's not functioning as expected. Oddly enough, when I test the same request using Postman, it works perfectly fine.

Despite trying various solutions found online, none have resolved my problem. One attempt involved modifying the header passed along with the request by including 'user-agent'.

 let header = new Headers({
   'Content-Type': 'application/json; charset=utf-8',
   'Authorization': 'console',
   'MacAddress': localStorage.getItem('macAddress'),
   'Key': localStorage.getItem('key'),
   'access-control-allow-origin': '*',
   'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.109 Safari/537.36'
 });
 let data = JSON.stringify({
   FirstName: this.FirstName,
   LastName: this.LastName,
   MI: this.u_mname,
   Address: this.Address,
   City: this.City,
   State: this.State,
   ZipCode: this.ZipCode,
   HomePhone: this.HomePhone,
   OfficePhone: this.OfficePhone,
   OfficePhoneExt: this.OfficePhoneExt,
   CellPhone: this.CellPhone,
   Fax: this.Fax,
   Email1: this.Email1,
   Email2: this.Email2,
   ContactTypeId: this.ContactTypeId,
   dob: this.dob,
   ApplicationId: this.ApplicationId
 });

 this.http.post(localStorage.getItem('base_url') + '/services/odata/tblContacts?Mother=0&Father=0&Guardian=0&groupIdList=0', data, { headers: header})
   .map(res => console.log(res))
   .subscribe(
      data => {
       alert(data)
     }, err => {
       alert(err)
     })

My anticipation was to receive a 'HTTP status code 201' as a response, however, what I get is a status code of 200 along with the message 'Internal Server Error. Please see details on server logs.'

Answer №1

If you're looking to implement something similar, consider the following code snippet:

let httpHeaders;

this.httpOptions = {
      headers: new HttpHeaders({ 
   'Content-Type': 'application/json; charset=utf-8',
   'Authorization': 'console',
   'MacAddress': localStorage.getItem('macAddress'),
   'Key': localStorage.getItem('key'),
   'access-control-allow-origin': '*',
   'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.109 Safari/537.36'
   })
    };

 let dataObj = JSON.stringify({
   FirstName: this.FirstName,
   LastName: this.LastName,
   MI: this.u_mname,
   Address: this.Address,
   City: this.City,
   State: this.State,
   ZipCode: this.ZipCode,
   HomePhone: this.HomePhone,
   OfficePhone: this.OfficePhone,
   OfficePhoneExt: this.OfficePhoneExt,
   CellPhone: this.CellPhone,
   Fax: this.Fax,
   Email1: this.Email1,
   Email2: this.Email2,
   ContactTypeId: this.ContactTypeId,
   dob: this.dob,
   ApplicationId: this.ApplicationId
 });

 this.http.post(
  localStorage.getItem('base_url') + '/services/odata/tblContacts?Mother=0&Father=0&Guardian=0&groupIdList=0', 
dataObj,
httpHeaders
}).map(response => console.log(response))
  .subscribe(
     responseData => {
       alert(responseData)
     }, error => {
       alert(error)
     })

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

Having difficulty connecting to the router within a container component for Angular2 routing

Presently, my code snippet looks like this: import { Router } from 'angular2/router'; @Component({...}) export class Index { constructor(public router: Router) { this.router.subscribe({...}); } } Although there are additional function ...

Refreshing Form after Saving in Angular 4

After clicking the Save button, I want to reset the form (addUserForm). I created a modal with a form to input user data. This form serves for both editing existing data and creating new data, with the flag 'Create' or 'Update' differen ...

Using 'interface' declarations from TypeScript is unsupported in JS for React Native testing purposes

I have a ReactNative app and I'm attempting to create a test using Jest. The test requires classes from a native component (react-native-nfc-manager), and one of the needed classes is defined as follows export interface TagEvent { ndefMessage: N ...

Clicking on a single checkbox causes the entire input to become deactivated due to the way the system is

I'm encountering a puzzling issue that has me feeling like I know the solution, yet I don't. I set "State" to [checked]. The problem arises when, upon turning it into a map and clicking just one checkbox, the entire selection is clicked. To addre ...

Creating a dynamic text design using Bootstrap or CSS: What's the best approach?

I attempted to enable responsive font sizes in Bootstrap 4.3.1 by setting the $enable-responsive-font-sizes variable to true, but I did not see any changes. Below is the code from my template.html file: <div class="m-2" id="role" ...

What is the correct way to handle the return value of an useAsyncData function in Nuxt 3?

How can I display the retrieved 'data' from a useAsyncData function that fetches information from a pinia store? <script setup lang="ts"> import { useSale } from "~/stores/sale"; const saleStore = useSale(); const { da ...

Ways to utilize the scan operator for tallying emitted values from a null observable

I'm looking for an observable that will emit a count of how many times void values are emitted. const subject = new Subject<void>(); subject.pipe( scan((acc, curr) => acc + 1, 0) ).subscribe(count => console.log(count)); subject ...

Angular: Converting JSON responses from HttpClient requests into class instances

I am facing an issue with the following code: public fetchResults(searchTerm: string): Observable<Array<SearchResult>> { let params = new HttpParams().set('searchTerm', searchTerm); return this.http .get<Array< ...

Learn how to successfully import a webp image into a React TypeScript project

I have looked everywhere for the answer, but I can't seem to find it When trying to import a *.webp image in typescript, you need to create a declaration file, like declaration.d.ts The declaration file should contain something similar to the foll ...

Executing an API call in Angular using a for-loop

I'm working on a project where I need to make multiple API calls based on the length of a mockInput.json file. Here's how I have implemented it: api.service.ts import { Injectable } from '@angular/core'; import { HttpClient, HttpHeade ...

Index.js is dynamically importing a .tsx file post-build, with a specific focus on Windows

While working on my project, I decided to customize a module by cloning it and making some changes. After installing the dependencies and building it, I encountered an error when trying to run it. The error message stated: Error: Unable to resolve module & ...

The absence of the function crypto.createPrivateKey is causing issues in a next.js application

For my next.js application, I am utilizing the createPrivateKey function from the crypto module in node.js. However, I encountered an issue as discussed in this thread: TypeError: crypto.createPrivateKey is not a function. It seems that this function was a ...

Using Javascript to parse SOAP responses

Currently, I am working on a Meteor application that requires data consumption from both REST and SOAP APIs. The SOAP service is accessed using the soap package, which functions properly. However, I am facing challenges with the format of the returned data ...

Exploring Typescript code through a practical example with reference to Uniswap's implementation

On the Uniswap website, I came across some code on the Swap page that caught my attention. You can find the code snippet in question at line 115 of the Uniswap GitHub repository. const { trade: { state: tradeState, trade }, allowedSlippage, cur ...

Examining the array to ensure the object exists before making any updates in the redux

Is there a way to determine if an object exists in an array and update it accordingly? I attempted to use the find method, but it couldn't locate the specified object. I also tried includes, but it seems to be unable to recognize the item within the ...

Updating the display in Angular 4 following modifications to an array

I am puzzled by a certain concept. I came across a notion that the view in my project only updates when some of the variables change their reference. However, I'm confused about how this applies to arrays. When I make changes to an array, sometimes th ...

What are the best practices for integrating PrimeVue with CustomElements?

Recently, I decided to incorporate PrimeVue and PrimeFlex into my Vue 3 custom Element. To achieve this, I created a Component using the .ce.vue extension for the sfc mode and utilized defineCustomElement along with customElements.define to compile it as a ...

What is the best way to implement switchMap when dealing with a login form submission?

Is there a better way to prevent multiple submissions of a login form using the switchMap operator? I've attempted to utilize subjects without success. Below is my current code. import { Subject } from 'rxjs'; import { Component, Output } ...

acquiring the main class instance within a function without relying on an arrow function

Within my Angular project, I have integrated a datatable with row grouping and row callbacks. Datatable Options openPositionDatatableOptions = { sDom: 'rt<"bottom"p>', ajax: (data, callback, settings) => { this.service.ge ...

Unable to transfer variable from a function to the test in Protractor

Currently, I am working on a test to verify the amount of gold in my possession. The test is being conducted using TypeScript and Protractor. Within this testing scenario, I have a method named GetAmountOfChips: public static GetAmountOfChips(): PromiseL ...