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

Radio buttons may not appear initially upon loading the first page

Can anyone explain why the radio buttons are not visible when the page first loads? I am using Angular Material's mat-radio-buttons. Click here for the code ...

Implementing reactivity in vue-chartjs using the Vue3 Composition API and data from an object

I have been struggling to update a Bar Graph dynamically whenever there is a change in the data object. Despite using reactive() and ref(), I am unable to achieve the desired functionality as the graph only updates upon page refresh. Below is my chart com ...

Incorporating a JavaScript npm module within a TypeScript webpack application

I am interested in incorporating the cesium-navigation JavaScript package into my project. The package can be installed via npm and node. However, my project utilizes webpack and TypeScript instead of plain JavaScript. Unfortunately, the package is not fou ...

What is the process for importing an mp3 file into a TypeScript project?

I'm currently working on a web application using React and TypeScript. My current challenge involves importing an mp3 file for use with the use-sound library, but I keep encountering this error in TypeScript: "Cannot find module '../../as ...

What determines the narrowing of a type when it is defined as a literal versus when it is returned from a function?

I'm really trying to wrap my head around why type narrowing isn't working in this scenario. Here's an example where name is successfully narrowed down: function getPath(name: string | null): "continue" | "halt" { if (n ...

The TypeScript class for Date has a property that outputs a string

In my TypeScript code, I have defined a model class as follows: export class Season { ID: number; Start: Date; } Below is an example of how this model class is utilized within a component: export class SeasonsComponent { seasons: Season[]; sele ...

Issue with iOS 10: Changes to class not reflected in CSS/styles

Currently, I am utilizing Ionic with Angular to develop an application for Android and iOS. Surprisingly, everything functions smoothly on Android, but there seems to be an issue with iOS. I am employing a class change on an element using ng-class. I can ...

"Unlock the power of NGXS by leveraging the raw state values

I'm having trouble locating an example in the NGXS documentation that demonstrates how to properly type the state object. Specifically, I am looking for guidance on typing the return value of the snapshot method of Store. For instance: this.store.sn ...

When creating utility classes, is it beneficial to offer a non-mutable API to facilitate their integration with frameworks such as React?

Currently, I am working on enhancing the functionality of my DateWithoutTime class. As part of this process, private fields within the class need to be updated by public methods. this.state.dateWithoutTimeInstance.shiftBySpecificDaysCount({ daysCount: 5, ...

What is the process for turning off minifying bundles when constructing an Angular application?

After developing an Angular project and implementing Server Side Rendering (SSR) using the angular-universal package, I have successfully served my project with SSR on port localhost:4000. Now, I am looking to debug it in a similar way as we do in the sour ...

Is it possible to retrieve the complete HTTP response text using Node.js from a HTTP module's .get response?

I have a straightforward web server set up: const ws = require('http'); ws.createServer( function(req,res) { console.log('request received'); res.write('Hello world'); res.end(); }) ...

Exploring the Concepts of Union and Intersection Types in Typescript

I am trying to wrap my head around Union and Intersection types in TypeScript, and I've come across a case that's puzzling me. You can check it out on this Playground Link interface A { a: number; } interface B{ b: boolean; } type Un ...

Using TypeScript with React and Material-UI: Issue with undefined theme in createStyles()

Currently, I am delving into React with TypeScript and utilizing the Material UI framework for the frontend. In my quest to activate media queries, an error has crossed my path: Uncaught TypeError: Cannot read property 'up' of undefined ...

Can you explain the meaning behind this TypeScript variable declaration syntax?

Can anyone explain the meaning of this code snippet: myCollection: Collection|any = null; I'm having trouble understanding it... Does it indicate that myCollection is set to type Collection, (which is an interface), with a default value of null? But ...

Transferring a variable from an Angular 2 constructor into the template via the then statement

I'm struggling with implementing a secure login system. My goal is to first check the device's native storage for an item named 'user', then verify if the user exists in our database, and finally retrieve the unique id associated with t ...

It is feasible to completely override a class in TypeScript

I have a subclass defined as follows: customException.ts /** * Custom Error class. * * @class Error * @extends {Error} */ class Error { /** * @type {string} * @memberof Error */ message: string; /** * @type {boolean} * @memberof ...

Encountering problem installing "kendo-angular-grid" via npm

I am currently working on a project that utilizes kendo. Here is the content of the package.json file: Package.json- { "name": "angular-2-webpack-starter", "version": "0.1.0", "description": "A starter kit for angular 2 and webpack", "scripts": { ...

What is the best way to obtain the value of a nested formBuilder group?

Currently, my nested form is structured like this: this.form = this.formBuilder.group({ user: this.formBuilder.group({ id: ['', Validators.required], name: ['', Validators.required], phone: ['' ...

Adding the "unsafe" keyword before the URL in the href attribute ensures that potentially harmful URLs are

When attempting to launch an app, everything goes smoothly with a static URL. However, when using a dynamic href tag in *ngFor, the URL is modified by adding an unsafe keyword which causes it to fail. Currently operating on Angular 6, I am retrieving an I ...

Implementing theme in Monaco editor without initializing an instance

I recently developed a web application incorporating Monaco Editor. To enhance user experience, I also integrated Monaco for syntax highlighting in static code blocks. Following guidance from this source, I successfully implemented syntax highlighting wit ...