Node.js React按钮,用于提交要添加到Firebase Cloud Firestore的快速后端Post请求

Node.js React按钮,用于提交要添加到Firebase Cloud Firestore的快速后端Post请求,node.js,reactjs,firebase,express,google-cloud-firestore,Node.js,Reactjs,Firebase,Express,Google Cloud Firestore,我有一个express.js后端处理路由和一些通过某些路由访问的模拟数据。此外,还有一个get请求和post请求,分别用于接收和向Firestore集合“books”添加文档 const express=require('express'); 常量app=express(); 常数端口=8000 const cors=要求(“cors”) const db=require('./firebase'); 使用(express.json()); 应用程序使用(cors()); 常数存储=[ { 作者

我有一个express.js后端处理路由和一些通过某些路由访问的模拟数据。此外,还有一个get请求和post请求,分别用于接收和向Firestore集合“books”添加文档

const express=require('express');
常量app=express();
常数端口=8000
const cors=要求(“cors”)
const db=require('./firebase');
使用(express.json());
应用程序使用(cors());
常数存储=[
{
作者:《约翰·斯内普》,
标题:“随机书”
},
{
作者:《赫尔曼·梅尔维尔》,
标题:《白鲸》
},
{
作者:《威廉·莎士比亚》,
标题:《哈姆雷特》
},
{
作者:《荷马》,
标题:《伊利亚特》
},
{
作者:《阿尔伯特·加缪》,
标题:“陌生人”
},
{
作者:《乔治·艾略特》,
标题:“米德尔马奇”
},
{
作者:《查尔斯·狄更斯》,
标题:《远大前程》
},
{
作者:《威廉·福克纳》,
标题:《喧哗与骚动》
},
]
//获取收藏“书籍”中的文档
app.get(“/books/get”),异步(req,res)=>{
const snapshot=await db.collection(“books”).get();
const books=[];
snapshot.forEach((doc)=>{
books.push({…doc.data(),id:doc.id});
});
res.send(书籍);
});
//向Firestore收藏“书籍”添加文档的Post请求
app.post(“/books/add”),异步(req,res)=>{
const{title,author}=req.body;
const resp=等待数据库集合(“书籍”)。添加({
标题:req.body.title,
作者:req.body.author,
});
res.sendStatus(200);
});
//访问模拟数据
app.get(“/api/stores”),函数(req,res){
res.json(存储)
})
//查询特定标题
app.get(“/api/stores/:title”),函数(req,res){
const query=req.params.title;
var结果=null;
对于(var指数=0;指数{
log(`示例应用程序正在侦听http://localhost:${port}`)
});
我知道上面对express服务器的请求工作正常,因为我已经测试了每个请求,并使用Postman处理了Post请求

现在,对于前端via react,我已经在一个列表中显示了来自商店(模拟数据)的标题和作者,并给列表中的每个元素一个按钮,该按钮将用于通过express('/books/add')的POST请求将其保存到Firestore集合。下面是该组件的react代码:

import React, { Component } from 'react';


export default class Search extends Component{
    constructor(props){
        super(props)
        this.state = {
            results: [],
            author: '',
            title: '',
        };
    }
//the below fetch is a get request that gets the elements from the stores variable in the express server.
    componentDidMount(){
        fetch('/api/stores')
        .then(res => res.json())
        .then(results => this.setState({results}, ()=> console.log('Books fetched...', results)));
    }
    

    render() {
        return (
          <div>
            <h2>result</h2>
            <ul>
            {this.state.results.map(resu => 
              <li key={resu.id}>{resu.title} - {resu.author}
              <button/>
              </li>
            )}
            </ul>
          </div>
        );
      }
    }
import React,{Component}来自'React';
导出默认类搜索扩展组件{
建造师(道具){
超级(道具)
此.state={
结果:[],
作者:'',
标题:“”,
};
}
//下面的fetch是一个get请求,它从express服务器中的stores变量获取元素。
componentDidMount(){
获取(“/api/stores”)
.then(res=>res.json())
.then(results=>this.setState({results},()=>console.log('Books fetched…',results));
}
render(){
返回(
结果
    {this.state.results.map(resu=>
  • {resu.title}-{resu.author}
  • )}
); } }

是否有人知道通过按钮的onClick执行POST请求的方法,以便将列表中该元素的相应标题和作者作为文档传递给Firestore集合?

这应该可以。您需要调用一个函数,在单击按钮时执行POST请求

import React, { Component } from 'react';


export default class Search extends Component{
    constructor(props){
        super(props)
        this.state = {
            results: [],
            author: '',
            title: '',
        };
    }
//the below fetch is a get request that gets the elements from the stores variable in the express server.
    componentDidMount(){
        fetch('/api/stores')
        .then(res => res.json())
        .then(results => this.setState({results}, ()=> console.log('Books fetched...', results)));
    }

    handleSave(data) {
        fetch('/books/add'
        {
            headers: {
               'Accept': 'application/json',
               'Content-Type': 'application/json'
            },
        method: "POST",
        body: JSON.stringify(data)
     })
        .then(function(res){ console.log(res) })
    }
    

    render() {
        return (
          <div>
            <h2>result</h2>
            <ul>
            {this.state.results.map(resu => 
              <li key={resu.id}>{resu.title} - {resu.author}
              <button onClick={() => this.handleSave(resu)}/>
              </li>
            )}
            </ul>
          </div>
        );
      }
    }
import React,{Component}来自'React';
导出默认类搜索扩展组件{
建造师(道具){
超级(道具)
此.state={
结果:[],
作者:'',
标题:“”,
};
}
//下面的fetch是一个get请求,它从express服务器中的stores变量获取元素。
componentDidMount(){
获取(“/api/stores”)
.then(res=>res.json())
.then(results=>this.setState({results},()=>console.log('Books fetched…',results));
}
handleSave(数据){
获取('/books/add'
{
标题:{
“接受”:“应用程序/json”,
“内容类型”:“应用程序/json”
},
方法:“张贴”,
正文:JSON.stringify(数据)
})
.then(函数(res){console.log(res)})
}
render(){
返回(
结果
    {this.state.results.map(resu=>
  • {resu.title}-{resu.author} this.handleSave(resu)}/>
  • )}
); } }
这应该可以。您需要调用一个函数,单击按钮即可执行post请求

import React, { Component } from 'react';


export default class Search extends Component{
    constructor(props){
        super(props)
        this.state = {
            results: [],
            author: '',
            title: '',
        };
    }
//the below fetch is a get request that gets the elements from the stores variable in the express server.
    componentDidMount(){
        fetch('/api/stores')
        .then(res => res.json())
        .then(results => this.setState({results}, ()=> console.log('Books fetched...', results)));
    }

    handleSave(data) {
        fetch('/books/add'
        {
            headers: {
               'Accept': 'application/json',
               'Content-Type': 'application/json'
            },
        method: "POST",
        body: JSON.stringify(data)
     })
        .then(function(res){ console.log(res) })
    }
    

    render() {
        return (
          <div>
            <h2>result</h2>
            <ul>
            {this.state.results.map(resu => 
              <li key={resu.id}>{resu.title} - {resu.author}
              <button onClick={() => this.handleSave(resu)}/>
              </li>
            )}
            </ul>
          </div>
        );
      }
    }
import React,{Component}来自'React';
导出默认类搜索扩展组件{
建造师(道具){
超级(道具)
此.state={
结果:[],
作者:'',
标题:“”,
};
}
//下面的fetch是一个get请求,它从express服务器中的stores变量获取元素。
componentDidMount(){
获取(“/api/stores”)
.then(res=>res.json())
.then(results=>this.setState({results},()=>console.log('Books fetched…',results));
}
handleSave(数据){
获取('/books/add'
{
标题:{
“接受”:“应用程序/json”,
“内容类型”:“应用程序/json”
},
方法:“张贴”,
正文:JSON.stringify(数据)
})
.then(函数(res){console.log(res)})
}
render(){
返回(
结果
    {this.state.results。