The error "TypeError: Cannot read property 'match' of undefined" occurs when trying to access the match property on an undefined value

Just a few minutes back, I set up a new project in the latest version of Ionic. I included

import { HTTP } from '@ionic-native/http'

and then proceeded to send a GET request to my backend application.

meetingsUrl: 'http://localhost:8080/test/all';
 this.http.useBasicAuth('login','password');
    this.http.get(this.meetingsUrl,{}, {'Content-Type':'application/json'})
      .then(data => {
        console.log(data);
      })
      .catch(error => {
        console.log(error);
      });

I'm using the 'ionic cordova run browser' command. I also attempted to run it on an android device, but encountered the same issue.

Unfortunately, in both scenarios, I encountered the following error:

TypeError: Cannot read property 'match' of undefined
    at getMatchingHostHeaders (advanced-http.js:118)
    at getMergedHeaders (advanced-http.js:126)
    at Object.get (advanced-http.js:210)
    at callCordovaPlugin (plugin.js:110)
    at plugin.js:136
    at util.js:22
    at new t (polyfills.js:3)
    at tryNativePromise (util.js:21)
    at getPromise (util.js:29)
    at wrapPromise (plugin.js:119)

Answer №1

You made a mistake. Make sure to configure the headers properly.

Refer to the documentation

get(url, parameters, headers)

Here is an example from the documentation:

    this.http.get('https://google.com/', {
      id: 12,
      message: 'test'
    }, { Authorization: 'OAuth2: token' }).then(data => {
       console.log(data.status);
       console.log(data.data); // data received by server
       console.log(data.headers);
  })
  .catch(error => {
      console.log(error.status);
      console.log(error.error); // error message as string
      console.log(error.headers);
  });

Answer №2

Here's an example of a LogIn request using the AppSignIn URL, which can be found at http://www.example.com/

public signInRequest(login:Login):Promise<OAuth> {
        let params:URLSearchParams = new URLSearchParams();
        params.set('userId', login.userId.toString());
        params.set('password', login.password.toString());
        let requestOption:RequestOptionsArgs = {
            search: params
        };
        return this.http
            .get(AppSignIn, requestOption)
            .toPromise()
            .then(this.extractData)
      }

Answer №3

Give it a shot:

attemptLogin(){

   let encodedCredentials = this.http.generateBasicAuthHeader("username", "password"); // returns an object like {Authorization: "Basic encodedUsernameAndPassword" } 

   this.http.fetch("url", {}, encodedCredentials).then((response)=>{
      //handling success 
      console.log(response); 
   }).catch((error)=>{
      //handling error 
      console.log(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

The command "npm start" is currently experiencing issues, showing an error message stating that it failed at the start script for the project

I have been using this link as an example to learn Angular. However, when I try to run npm start, it shows an error. I have looked for solutions and they suggest updating either npm or Angular versions, but I am already using the latest versions: npm -v = ...

Issue encountered when testing Angular 7 with Jest: Kendo Intl Service lacking locale information

After running multiple tests on a specific numeric component that deals with locale formatting, everything was working fine with Karma. But when we switched to Jest, an error reared its ugly head: NoLocale: Missing locale info for 'de-DE' Soluti ...

What is the best way to define ngOptionValue for my ng-option selection?

After updating my select/option code to include a search feature, it caused an issue with my function create. Here is the HTML code: <div class="input-group"> <label htmlFor="categoria" class="sr-only"> ...

Ensure that the tooltip remains visible within the confines of the page

In my Angular application, I have successfully implemented a versatile tooltip feature that goes beyond just displaying text. The tooltip is a div element that has the ability to contain various contents: .tooltip-master { position: relative; .tooltip ...

Utilizing Typescript with Vue 3's Injection Feature

Using the new Vue 3 Composition API, I have created a "store" for reactive data. const state = reactive<State>({ accessToken: undefined, user: undefined, }); export default { state: readonly(state), } When my app is created, I pass the store ...

Unable to initialize default values on Form Load in Angular Reactive Forms

My goal is to make an HTTP request by passing an ID, then take the response and assign the values to form fields. I attempted using setValue and patchValue methods, but they did not yield the desired results. spService itemData = new ItemData() getIte ...

In Angular, encountering difficulty accessing object members within an array when using custom pipes

Here is a custom pipe that I have created, but I am facing an issue accessing the members of the customfilter array, which is of type Item. import { Pipe, PipeTransform } from '@angular/core'; import {Bus} from '/home/pavan/Desktop/Pavan ...

Can we modify the styling of elements in Angular based on an object property?

I have a class named Task with the following properties: export class Task { name: string; state: number; } Within my component.ts file, I have an array of objects consisting of instances of the Task class (tasks). When displaying them in the tem ...

Exploring the capabilities of Vue combined with Typescript and Audio Worklets

I've encountered a challenge with configuring Vue to compile audio worklets. Specifically, I am facing a similar issue to this problem that has already been resolved, but using Typescript instead of JavaScript. My approach was to include the ts-loader ...

Functionality not functioning within Shadow DOM

After creating and exporting an Angular Element as a single script tag (user-poll.js), using the element on a host site is simple. Just include the following two lines: <user-poll></user-poll> <script src="path/to/user-poll.js"></sc ...

How come the inference mechanism selects the type from the last function in the intersection of functions?

type T = (() => 1) & (() => 2) extends () => infer R ? R : unknown What is the reason that T is not never (1 & 2)? Does the type always come from the last function, or can it come from one of them? ...

PhpStorm flawlessly detects ES7 type hinting errors

For my project, I have implemented TypeScript. While JavaScript's array includes() function has been valid since ECMA6, setting the lib parameter in tsconfig to "es6" results in a non-fatal error being thrown in the browser console when using the foll ...

The call to react.cloneElement does not match any overloads

I'm encountering a typescript error in my React code when using React.cloneElement with the first parameter "children", and I am unsure of how to resolve it. As a newcomer to typescript, I believe that the type definitions in index.d.ts for cloneElem ...

What is the best way to access an object's key within an array using TypeScript?

How can I access the key values of the objects stored in a predefined array? const temp = [ { key: "name", value: "mike" }, { key: "gender", value: "male" }, ]; I am interested in retrieving the key values, such as name and gender, from the objects wi ...

Managing plain text and server responses in Angular 2: What you need to know

What is the best way to handle a plain text server response in Angular 2? Currently, I have this implementation: this.http.get('lib/respApiTest.res') .subscribe(testReadme => this.testReadme = testReadme); The content of lib/respApi ...

"Why does the function not work inside the template, but works when the logic is set inside the template

My logic was working perfectly -> for example: Everything was working fine until I tried to set my values inside ts and switch logic in ts.file component. But when I did it inside the ts file, it stopped working: It's not working anymore. Why i ...

Leveraging multiple routes for a single component in Angular 6

Creating a component named Dashboard for admin requires passing the username in the route to find user information. This is the routing setup: {path:'dashboard/:username',component:DashboardComponent,children:[ {path:'role',component: ...

Navigating between two different HTML pages using Angular 2 routing

In my Angular2 application, I have both a front-end section and an admin interface. The front-end section is styled with its own unique set of styles defined in the index.html file. On the other hand, the admin interface has a completely different set of ...

How does the use of nodejs, a server-side scripting language, tie into ReactJs or other front-end languages?

Can Node, being a server-side scripting language, be effectively utilized in the development of front-end applications such as npx create-react-app or npx create-nuxt-app? ...

What is the best way to enable external access to a class component method in React and Typescript?

I am currently working on a component library that compiles to umd and is accessible via the window object. However, I need to find a way to call a class component's methods from outside the class. The methods in my classes are private right now, but ...