我做了一個應用程式來發送推送通知,我成功地發送了通知。但是我有一個問題,那就是我想保存我在資料庫中發送的任何通知,
這是代碼,
var FCM = require("fcm-node");
const express = require("express");
const mongoose = require("mongoose");
require("dotenv/config");
const app = express();
app.use(express.json());
const notificationSchema = mongoose.Schema({
name: String,
});
const NotificationModel = mongoose.model("Notification", notificationSchema);
app.post("/fcm", async (req, res, next) => {
try {
let fcm = new FCM(process.env.SERVER_KEY);
let message = {
to: req.body.token,
notification: {
title: req.body.title,
body: req.body.body,
},
};
fcm.send(message, function (err, response) {
if (err) {
next(err);
} else {
// res.json(response);
// res.send(message.notification.body);
app.post("/notfs", async (req, res) => {
let newNotf = new NotificationModel({
name: message.notification.body,
});
newNotf = await newNotf.save();
res.send(newNotf);
});
}
});
} catch (error) {
next(error);
}
});
app.get("/notfs", async (req, res) => {
const notfs = await NotificationModel.find();
res.send(notfs);
});
mongoose
.connect(process.env.CONNECTION_STRING)
.then(() => {
console.log("connected");
})
.catch((err) => {
console.log(err);
});
app.listen(3000, () => {
console.log("listened");
});
為什么它不在資料庫中保存通知?
另一個問題請如果有比這更好的方法,請留下并謝謝? 提前致謝
uj5u.com熱心網友回復:
使用axiospackage,這是 nodejs 官方推薦的。它就像 jquery ajax 呼叫一樣簡單
uj5u.com熱心網友回復:
試試看
var FCM = require("fcm-node");
const express = require("express");
const mongoose = require("mongoose");
require("dotenv/config");
const app = express();
app.use(express.json());
console.log(process.env.CONNECTION_STRING);
const notificationSchema = mongoose.Schema({
name: String,
});
const NotificationModel = mongoose.model("Notification", notificationSchema);
app.get("/notfs", async (req, res) => {
const list = await NotificationModel.find();
res.send(list);
});
app.post("/fcm", async (req, res, next) => {
let newNotf = new NotificationModel({
name: req.body.body,
});
try {
let fcm = new FCM(process.env.SERVER_KEY);
let message = {
to: req.body.token,
notification: {
title: req.body.title,
body: req.body.body,
},
};
fcm.send(message, async function (err, response) {
if (err) {
next(err);
} else {
res.json(response);
newNotf = await newNotf.save();
}
});
} catch (error) {
next(error);
}
});
mongoose
.connect(process.env.CONNECTION_STRING)
.then(() => {
console.log("connected");
})
.catch((err) => {
console.log(err);
});
app.listen(3000, () => {
console.log("listened");
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/368435.html
上一篇:在專案中更改vue版本
