如何使用Firebase Node.js添加数据

时间:2019-03-12 21:39:54

标签: node.js firebase

我是Firebase和node.js的新手。如何发出简单的POST请求以将数据添加到Firebase数据库?

const functions = require("firebase-functions");
const express = require("express");
const firebase = require("firebase");

const app = express();

// Initialize Firebase
var config = {
  apiKey: "*****",
  authDomain: "***",
  databaseURL: "https://",
  projectId: "***",
  storageBucket: "888",
  messagingSenderId: "22"
};
if (!firebase.apps.length) {
  firebase.initializeApp(config);
}

var db = firebase.firestore();
////////////////////////DB Calls//////////////////
//get all users

app.get("/Users", (req, res) => {
  var cityRef = db.collection("Users");

  var users = [];

  var getDoc = cityRef
    .get()
    .then(snapshot => {
      snapshot.forEach(doc => {
        // console.log(doc.id, "=>", doc.data());
        users.push(doc.data());
      });
      res.send(users);
    })
    .catch(err => {
      console.log("Error getting document", err);
    });
});



var router = express.Router();


app.get('/', function (req, res) {
  console.log("HTTP Get Request");
  res.send("HTTP GET Request");
});

app.put('/', function (req, res) {
  console.log("HTTP Put Request");
  res.send("HTTP PUT Request");
});

router.post('/AddUser', function (req, res) {


  db.collection("Users").doc("LA").set({
    Descn: "Los Angeles",
  })
  .then(function() {
    console.log("Document successfully written!");
  })
  .catch(function(error) {
    console.error("Error writing document: ", error);
  });



  console.log("HTTP POST Request");
  res.send("HTTP POST Request");  
});

app.delete('/', function (req, res) {
  console.log("HTTP DELETE Request");
  res.send("HTTP DELETE Request");
});



app.get("/home", (req, res) => {
  res.send("Hello from express app inside firebase cloud functions");
});
app.get("/secondhome", (req, res) => {
  res.send("Hello from express app again");
});




exports.app = functions.https.onRequest(app);

Lorem Ipsum只是印刷和排版行业的伪文本。自1500年代以来,Lorem Ipsum一直是行业的标准伪文本,当时一位不知名的打印机拿起一个厨房,将其打乱成一本样本书。

0 个答案:

没有答案