Issues arise when attempting to send a POST request from mobile devices running IONIC ANGULAR

I need assistance with sending push notifications to all devices through a Firebase function.

Here is the Firebase Function code:

const functions = require("firebase-functions");
const express = require("express");
const bodyParser = require("body-parser");
const cors = require('cors');
const request = require('request-promise');
const app = express();
const main = express();

main.use(cors())
main.use('/api/v1', app);
main.use(bodyParser.json());
main.use(bodyParser.urlencoded({ extended: false }));

app.post('/sendNotification', function(req, res) {  
  console.log(req.body)

  let notification = {
    "to" :  req.body.token,
    "collapse_key" : "type_a",
    "notification" : {
        "body" : "Body of Your Notification",
        "title": "Title of Your Notification"
    },
    "data" : {
        "body" : "Body of Your Notification in Data",
        "title": "Title of Your Notification in Title",
        "key_1" : "Value for key_1",
        "key_2" : "Value for key_2"
    }
   };
    
    const options = {
      method: 'POST',
      uri: 'https://fcm.googleapis.com/fcm/send',
      body: notification,
      json: true,
      headers: {
          'Content-Type': 'application/json',
          'Authorization': 'key=MY KEY'
      }
    }
    
    request(options).then(function (response){
      res.status(200).json(response);
    })
    .catch(function (err) {
      console.log(err);
    })    
});

exports.sendSms = functions.https.onRequest(main);

In my Angular Application,

  sendNotification() {
    alert('Called, ddd');

    this.http.post(this.settings.sendNotification, { token: this.token }).subscribe(res => {
      alert('API CALLED');
      console.log(res)
    });
  }

Although the sendNotification function is triggered on the emulator devices, the API subscribe alert does not execute as expected. Can anyone offer guidance?

Please provide assistance. Thank you!

Answer №1

If you're facing any issues, this plugin should provide a solution for you.

  1. Start by using these commands to install the native http plugin:

    npm install cordova-plugin-advanced-http

    npm install @ionic-native/http

  2. Next, import the plugin into your module with:

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

  3. Finally, include the plugin in your service/page/component and inject it in your constructor. This plugin is CORS safe and only functions on Android emulator/device.

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

Is it possible to target a specific element using Angular2's HostListener feature? Can we target elements based on their class name?"

Is there a way in Angular2 to target a specific element within the HostListener decorator? @HostListener('dragstart', ['$event']) onDragStart(ev:Event) { console.log(ev); } @HostListener('document: dragstart' ...

Can ngx permissions in angular be trusted for ACL management?

Currently working with Angular 6 and looking to manage user access control. While the conventional wisdom is to handle ACL in the backend, there are packages like ngx permissions available for managing it on the frontend. Is it secure to utilize these fe ...

Adding the unzip feature is not within my capabilities

I am a novice Japanese web developer. Unfortunately, my English skills are not great. I apologize for any inconvenience. I am interested in utilizing this specific module: https://www.npmjs.com/package/unzip To do so, I executed the following commands ...

Issue with Angular caused by Bootstrap node module

I encountered an issue when trying to run ng serve, receiving an error related to my node_modules. I suspect that moving a file into another folder may have caused this problem, but I'm unsure how to resolve it. bootstrap node_module error Additiona ...

Adjust the alignment of divs in Angular

In developing a dashboard, I have successfully displayed key value pairs in a component by retrieving them from an environment.ts file. Now, I am looking to rearrange the positioning of the individual testcard components to align with a specific layout sho ...

Potential null object detected when using a ref(null)

After reading the Vue Composition API documentation, it seems I should be utilizing ref(null) within a sub-component located inside <template>...</template>. Within this sub-component, there are methods such as open(), and my current approach ...

Angular data binding is not reflecting updates

Currently delving into the depths of Angular 2+, I find myself perplexed by the intricacies of bindings. Despite my best efforts on Google, the missing piece still eludes me after half an hour of searching. On a page, there lies a humble button whose text ...

Angular: controller's property has not been initialized

My small controller is responsible for binding a model to a UI and managing the UI popup using semantic principles (instructs semantic on when to display/hide the popup). export class MyController implements IController { popup: any | undefined onShow(con ...

Mastering the manipulation of complex nested objects within React state

Welcome, fellow developers! I am a junior developer currently working on a project that involves a large nested object structure (see example below). I am looking for the best approach to use this as a React state that can be accessed from multiple compon ...

Tips for passing a function and an object to a functional component in React

I am struggling with TypeScript and React, so please provide clear instructions. Thank you in advance for your help! My current challenge involves passing both a function and an object to a component. Let's take a look at my component called WordIte ...

Challenges with the Placeholder and Text Alignment in Angular Material's Text Area

I am currently facing an issue with a textarea in Angular, which is displayed as shown below: https://i.sstatic.net/jjUlT.png My Angular code for the textarea is as follows: <div *ngIf="whetherDisplay()" class="textarea-text"> <mat-form-field ...

What could be causing the QullJS delta to display in a nonsensical sequence?

The outcome showcased in the delta appears as: {"ops":[{"retain":710},{"insert":" yesterday, and she says—”\n“The clinic?","attributes":{"prediction":"prediction"}},{"del ...

What is the best way to retrieve the most recent entry in a Firebase real-time database?

Utilizing Firebase's real-time database, I am updating values in a chart as they change. However, my struggle lies in retrieving only the most recent value added to the database. While browsing through limitToLast and 'child_added' do not w ...

Mat Progress Bar for Tracking Fetch API Requests and Generating XLS Files

I am interested in implementing a mat progress bar to track the progress made while fetching data from the database and creating an XLSX file. The progress does not need to be exact, rough estimates and sudden changes are acceptable. Is it feasible to achi ...

Cypress - RangeError: The Date.toISOString method is throwing an error due to an invalid time

Running cypress version 13.9.0, I encountered a RangeError while using cy.reload(). The error points to an Invalid time value at Date.toISOString. Any suggestions on how to resolve this issue? waitForUpdate(employeeId, employeeName, employeeEmail) { ...

I want my Angular 2 application to redirect to the appropriate page when a user who is logged out attempts to access a page that requires them to be logged in

When a user is logged out in Angular 2 router and they try to navigate to a page that requires them to be logged in, I need the app.ts file to redirect them. I am utilizing typescript along with angular 2. Oddly enough, the redirection works for certain ...

Leveraging Vue mixin within a @Component

After implementing the vue-property-decorator package, I encountered an issue when trying to use a mixin method inside the beforeRouteEnter hook. Here is what I initially tried: import { Component, Mixins } from 'vue-property-decorator'; import ...

Importing SCSS files with scope restrictions

I'm currently working on importing an SCSS file into others to style them, with a "scoped" import in mind for better organization. Let me provide some code examples to clarify my point. File A ion-content { --padding-end: 10px; --padding-start: ...

Move all the attributes from one object stored in an array to another object within the same array using JavaScript or TypeScript

Is there a more efficient way to copy or move properties from one object within an array to another object? I've devised a simple logic that works, but I'm confident there must be a better approach. Can anyone offer some advice? var first = [ ...

Implementing Angular2 with conditional loading

One of the requirements for my project is to redirect users to the login page before loading the Angular2 application, without actually loading it. The project is built using angular2-quicksart. After minifying the Angular2 js file: <script> va ...