You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular向Firebase发送推送通知报错,Flutter无法接收数据库更新通知

解决Angular向Firebase发送推送通知的POST请求错误

嘿,我看你在尝试从Angular给Flutter应用发Firebase推送时碰到了请求失败的问题,这几个核心问题得先修正:

1. 用错了API地址!

你现在用的https://console.firebase.google.com/project/dummy-project-123/是Firebase控制台的网页链接,根本不是FCM的推送API接口。正确的主题消息推送地址应该是:

https://fcm.googleapis.com/fcm/send

2. 缺少身份验证和格式头

FCM要求请求必须带两个关键请求头:

  • Content-Type: application/json:告诉服务器你发的是JSON格式数据
  • Authorization: key=你的服务器密钥:用Firebase项目的服务器密钥做身份校验

你可以去Firebase控制台的「项目设置」→「云消息传递」里找到这个服务器密钥(Server key),别泄露给别人哦。

3. 小细节修正

你的消息体里有个拼写错误Angualr,虽然不影响功能,但建议改成Angular;另外topic字段的位置是对的,保持和notification、data同级就好。

修复后的完整代码

CustomService 服务代码

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class CustomService {
  // 正确的FCM推送API端点
  private fcmApiUrl = 'https://fcm.googleapis.com/fcm/send';
  // 替换成你自己的Firebase服务器密钥
  private serverKey = 'YOUR_FIREBASE_SERVER_KEY';

  // 修正拼写后的消息体
  myNotification = {
    notification: {
      title: 'Angular Notification',
      body: 'Displayed from Angular: App is in background or closed!'
    },
    data: {
      title: 'Angular Notification',
      body: 'Displayed From Angular: App is open',
      click_action: 'FLUTTER_NOTIFICATION_CLICK'
    },
    topic: 'all_users'
  };

  constructor(private http: HttpClient) { }

  pushNotification(): Observable<Object> {
    // 配置请求头
    const headers = new HttpHeaders({
      'Content-Type': 'application/json',
      'Authorization': `key=${this.serverKey}`
    });

    return this.http.post<Object>(this.fcmApiUrl, this.myNotification, { headers });
  }
}

AppComponent 组件代码

import { Component } from '@angular/core';
import { CustomService } from './custom.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  // 服务名首字母小写,符合Angular命名习惯
  constructor(private customService: CustomService) { }

  onButtonClick() {
    this.customService.pushNotification().subscribe(
      (response) => console.log('推送成功:', response),
      (error) => console.error('推送失败详情:', error) // 加个错误捕获,方便排查问题
    );
  }
}

额外提醒

  • 确保你的Flutter应用已经正确配置FCM,并且订阅了all_users这个主题,不然收不到消息
  • 开发环境下如果碰到CORS错误,建议给Angular配置代理,或者用后端转发请求(生产环境一定要用后端发,别把服务器密钥暴露在前端)
  • 要是还报错,看浏览器控制台的错误码:401是密钥无效,400是消息格式错,照着排查就行

内容的提问来源于stack exchange,提问作者usersina

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 16:37:46