The issue with Ionic 2 and Angular 2 is that the http Headers are not getting included in the request

I'm currently working with the latest beta release of Ionic and I've encountered an issue with sending headers along with an HTTP POST request to my API server. The code snippet I used is as follows: ** Ionic version - Beta-8 & Angular version -rc.3

import {Page,App,NavParams} from 'ionic-angular';
import {Headers, Http, RequestOptions} from '@angular/http';
import {Component} from '@angular/core';
import 'rxjs/add/operator/map';

@Component({
    templateUrl : 'build/pages/xyz/xyz.html'
})

export class Xyz{

    form:any;
    token:any;
    constructor(public app:App, navParams:NavParams, public http:Http){

        let code = {abc : 'abc'};
        let headers = new Headers();
        let body = JSON.stringify(code);
        headers.append('Content-Type', 'application/json');
        headers.append('Authorization', 'Bearer ' + "tokenContent");
        let options =new RequestOptions({headers : headers, body:body});
        this.http.post('http://myserver/myapi', options)
            .map(res => res.json())
            .subscribe(
                data=>{
                    console.log(data.message);
                },
                err=>{
                    console.log(err);
                },
                ()=>{
                    console.log("Process Complete");
                }
            );

Upon checking the console.log, both the options object and headers are properly set. However, when I actually make the HTTP request, neither the headers nor the body are being sent when enclosed in the options object. Surprisingly, when I attempt to send the body alone, it does show up in the request payload.

Answer №1

When using http.post, make sure to include the body as the second parameter for successful functionality:

headers.append('Content-Type', 'application/json');
headers.append('Authorization', 'Bearer ' + "tokenContent");
let options = new RequestOptions({ headers: headers });

this.http.post('http://myserver/myapi', body, options)
    .map(...

Answer №2

If you're having trouble testing from your browser, make sure to review the documentation regarding CORS requests.

Answer №3

Before proceeding, it's important to determine if the issue is related to CORS.

Additionally, you can experiment with the following code snippet:

let headers = new Headers();
headers.append('Content-Type','application/x-www-form-urlencoded; charset=UTF-8');
this.http.post(`${this.link}`,'sRequest=' + sRequest1,{ headers: headers });

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

Can you explain the concept of F-Bounded Polymorphism in TypeScript?

Version 1.8 of TypeScript caught my attention because it now supports F-Bounded Polymorphism. Can you help me understand what this feature is in simple terms and how it can be beneficial? I assume that its early inclusion signifies its significance. ...

Step-by-step guide for resolving the issue of "Observable.share is not recognized as a function" in Angular 2

When working with cache structure in Ionic 2, I often encounter an error when defining an observable array to store data retrieved from the server. How can I troubleshoot this issue and resolve it? marketArray : Observable<any>; /* GLOBAL */ th ...

Exploring type delegation in TypeScript

Here is a scenario where I am using the builder pattern in my code: export class ValidationBuilderBase implements IValidationBuilder { public isRequired(): IValidationBuilder { const validationResult = Validators.required(this.baseControl); ...

Guide on translating text in Angular Material Snackbar using ngx translate

I have successfully integrated ngx translate into my project, allowing me to convert text on HTML pages into different languages using JSON files. However, I am facing a challenge in changing the language of the text displayed in the "Snackbar" component i ...

When the application initializes, the Child Component is activated

There's a scenario where I need to trigger a component named 'cancellation' when the user clicks a button in another component called 'names'. To achieve this, I set a flag called loadCancellation to true when the Search button is ...

Angular allows you to pass an array of objects as FormData items

Is there a way to send FormData with an array of objects to an API? I have attempted the following: https://i.stack.imgur.com/BlYby.png This is the request payload. How can I retrieve all items with other data from my .NET Core C# API? public class Back ...

Angular - Transform calendar dates to a lively green upon initial popup activation

I'm looking to customize my calendar so that all the dates in my list have a green background when the calendar is opened. ngOnInit(): void { this.roomService.getReservableDatesFromRoom(room.roomName).subscribe(data => { for (let i = 0; i ...

a guide to caching a TypeScript computed property

I have implemented a TypeScript getter memoization approach using a decorator and the memoizee package from npm. Here's how it looks: import { memoize } from '@app/decorators/memoize' export class MyComponent { @memoize() private stat ...

Is there a more efficient approach to displaying a list of elements and sharing state in React with TypeScript?

Check out this code sample I'm attempting to display a list with multiple elements and incorporate a counter on the main element that updates every time one of the buttons is clicked. I'm uncertain if this approach is optimal, as I am transition ...

Unable to locate the image file path in React.js

I'm having trouble importing images into my project. Even though I have saved them locally, they cannot be found when I try to import them. import {portfolio} from './portfolio.png' This leads to the error message: "Cannot find module &apos ...

Cypress - AG-Grid table: Typing command causing focus loss in Cell

Encountering a peculiar issue: I am attempting to input a value into the cell using 'type()'. My suspicion is that each letter typed causes the focus on the cell to be lost. It seems that due to this constant loss of focus and the 'type()& ...

Display your StencilJs component in a separate browser window

Looking for a solution to render a chat widget created with stenciljs in a new window using window.open. When the widget icon is clicked, a new window should open displaying the current state while navigating on the website, retaining the styles and functi ...

Utilizing Angular's reactive forms to populate an array field with an array of data

I am currently using Angular 6 along with Reactive form to create a form. Within the ngOnInit() function, I have set up a form group in the following manner: this.landingPageForm = this.formBuilder.group({ title: new FormControl('', [ Val ...

The Angular 4 application fails to refresh automatically after saving changes in the HTML, CSS, or TS files

Software versions: Angular CLI: 1.6.1 Node: 8.2.1 Operating System: linux x64 Additionally, the devDependencies include: "devDependencies": { "@angular/cli": "1.3.2", "@angular/compiler-cli": "4.0.0", "@angular/language-service": "4.2.4", } ...

What is the best method to store GPS coordinates in the background every 10 minutes?

Is it possible to automatically store GPS location in the background at set intervals (e.g. every 5, 10, or 20 minutes) and save it to localStorage? Thank you! ...

What imports are needed for utilizing Rx.Observable in Angular 6?

My goal is to incorporate the following code snippet: var map = new google.maps.Map(document.getElementById('map'), { zoom: 4, center: { lat: -25.363, lng: 131.044 } }); var source = Rx.Observable.fromEventPattern( function (han ...

The inline script was denied execution as it breaches the Content Security Policy directive: "script-src 'self'"

While attempting to utilize an inline script in my project, I am continually encountering the following error message: 'Refused to execute inline script because it violates the following Content Security Policy directive: "script-src 'self'" ...

What is the process for updating button text upon clicking in Angular?

To toggle the text based on whether this.isDisabled is set to false or true, you can implement a function that changes it when the button is clicked. I attempted to use this.btn.value, but encountered an error. import { Component } from '@angular/core ...

An error has occurred while attempting to differentiate '[object Object]'. In Angular, only arrays and iterables are permitted for this operation

Can someone help me with resolving the error I am encountering while trying to display data on the front end? service.ts rec_source(){ var headers = new HttpHeaders().set('Authorization', 'Token ' + localStorage.getItem('u ...

Conceal optional navigation bar options once a user has logged in - utilizing Angular 8

I need assistance with hiding certain links in my navbar once a user has logged in. Below are the current navbar menus: <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav ml-auto"> <li class="nav ...