У меня есть функция callBackend(), которая отправляет уведомления. Он отлично работает в веб-браузере, и уведомления отправляются без каких-либо проблем. Однако когда я запускаю тот же код на устройстве Android, уведомления не срабатывают.
Кто-нибудь сталкивался с подобной проблемой или знает, что может быть причиной этого? Будем очень признательны за любую помощь!
ошибка:
Строка 1 – Msg: ошибка отправки уведомления: {"headers":{"normalizedNames":{},"lazyUpdate" :null,"headers":{}},"status":0,"statusText":"Неизвестная ошибка","url":"http://localhost:3000/notify","ok":false,"name ":"HttpErrorResponse","message":"Ответ об ошибке HTTP для http://localhost:3000/notify: 0 Неизвестная ошибка","error":{"isTrusted":true}
home.page.ts
import { Component } from "@angular/core";
import {
FirebaseMessaging,
GetTokenOptions,
} from "@capacitor-firebase/messaging";
import { Capacitor } from "@capacitor/core";
import { IonicModule } from "@ionic/angular";
import { environment } from "src/environments/environment";
import { NotificationService } from '../services/notification.service';
@Component({
selector: "app-home",
templateUrl: "home.page.html",
styleUrls: ["home.page.scss"],
standalone: true,
imports: [IonicModule],
})
export class HomePage {
public token = "";
constructor(
private notificationService: NotificationService
) {
FirebaseMessaging.addListener("notificationReceived", (event) => {
console.log("notificationReceived: ", { event });
});
FirebaseMessaging.addListener("notificationActionPerformed", (event) => {
console.log("notificationActionPerformed: ", { event });
});
if (Capacitor.getPlatform() === "web") {
navigator.serviceWorker.addEventListener("message", (event: any) => {
console.log("serviceWorker message: ", { event });
const notification = new Notification(event.data.notification.title, {
body: event.data.notification.body,
});
notification.onclick = (event) => {
console.log("notification clicked: ", { event });
};
});
}
}
public async requestPermissions(): Promise {
await FirebaseMessaging.requestPermissions();
}
public async getToken(): Promise {
const options: GetTokenOptions = {
vapidKey: environment.firebase.vapidKey,
};
if (Capacitor.getPlatform() === "web") {
options.serviceWorkerRegistration =
await navigator.serviceWorker.register("firebase-messaging-sw.js");
}
const { token } = await FirebaseMessaging.getToken(options);
this.token = token;
}
public async callBackend() {
console.log("call backend", this.token);
// Ensure you have the token before making the request
if (!this.token) {
console.error("Token not available. Make sure you call getToken() first.");
return;
}
const notificationData = {
token: this.token, // Include the token in the data
notification: {
title: 'Test Notification',
body: 'This is a test notification'
},
data: {
detailsId: '123'
}
};
// Send the request to the backend
this.notificationService.sendNotification(notificationData).subscribe(
(response) => {
console.log('Notification sent successfully:', response);
},
(error) => {
console.error('Error sending notification:', error);
}
);
}
}
index.js:
import express from "express";
import request from "request";
import { google } from "googleapis";
import { readFile } from "fs/promises";
import cors from 'cors';
const app = express();
const port = 3000;
// Use the CORS middleware
app.use(cors());
app.use(express.json());
// Function to get Google Cloud access token
async function getAccessToken() {
try {
const key = JSON.parse(await readFile(new URL('./angular-firebase-app-b7d17-firebase-adminsdk-3mx51-041a7cc2e5.json', import.meta.url)));
const SCOPES = ['https://www.googleapis.com/auth/cloud-platform'];
const jwtClient = new google.auth.JWT(
key.client_email,
null,
key.private_key,
SCOPES,
null
);
const tokens = await jwtClient.authorize();
console.log('Access Token:', tokens.access_token);
return tokens.access_token;
} catch (error) {
console.error('Error retrieving access token:', error);
throw new Error('Failed to retrieve access token');
}
}
// Route to send push notification
app.post('/notify', async (req, res) => {
const { token, notification, data } = req.body;
if (!token) {
return res.status(400).json({ error: 'Token is required' });
}
console.log('Notification Data:', notification, data);
console.log('Token:', token);
try {
const accessToken = await getAccessToken(); // Get access token
// Send FCM notification
const options = {
method: 'POST',
url: 'https://fcm.googleapis.com/v1/projects/ ... sages:send',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${accessToken}`, // Using the Google Cloud access token
},
body: JSON.stringify({
message: {
token: token,
notification: {
title: notification.title,
body: notification.body,
},
data: data,
},
}),
};
request(options, (error, response, body) => {
if (error) {
console.error('Error sending push:', error);
return res.status(500).json({ error: 'Failed to send notification' });
}
console.log('Push sent successfully:', body);
res.json({ success: true, message: 'Notification sent!' });
});
} catch (error) {
console.error('Error sending notification:', error);
res.status(500).json({ error: 'Internal Server Error' });
}
});
// Start server
app.listen(port, () => {
console.log(`Backend running at http://localhost:${port}`);
});
notification.service.ts:
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root',
})
export class NotificationService {
private apiUrl = 'http://localhost:3000/notify';
constructor(private http: HttpClient) {}
sendNotification(notificationData: any): Observable {
return this.http.post(this.apiUrl, notificationData);
}
}
Подробнее здесь: https://stackoverflow.com/questions/790 ... the-device
Angular – Push-уведомление Firebase node.js отправляет уведомление на устройство ⇐ Android
-
- Похожие темы
- Ответы
- Просмотры
- Последнее сообщение
-
-
Angular – Push-уведомление Firebase node.js отправляет уведомление на устройство
Anonymous » » в форуме Android - 0 Ответы
- 18 Просмотры
-
Последнее сообщение Anonymous
-