我有一个express.js后端,它处理通过某些路由访问的路由和一些模拟数据。此外,还有一个get请求和post请求,分别用于接收文档和将文档添加到Firestore集合“book”。
const express = require('express');
const app = express();
const port = 8000
const cors = require("cors")
const db = require('./firebase');
app.use(express.json());
app.use(cors());
const stores = [
{
author: 'John Snape',
title: 'Random Book'
},
{
author: 'Herman Melville',
title: 'Moby Dick'
},
{
author: 'William Shakespeare',
title: 'Hamlet'
},
{
author: 'Homer',
title: 'The Iliad'
},
{
author: 'Albert Camus',
title: 'The Stranger'
},
{
author: 'George Eliot',
title: 'Middlemarch'
},
{
author: 'Charles Dickens',
title: 'Great Expectations'
},
{
author: 'William Faulkner',
title: 'The Sound and the Fury'
},
]
//Getting documents in collection "books"
app.get("/books/get", async (req, res) => {
const snapshot = await db.collection("books").get();
const books = [];
snapshot.forEach((doc) => {
books.push({ ...doc.data(), id: doc.id });
});
res.send(books);
});
//Post request for adding document to Firestore Collection "books"
app.post("/books/add", async (req, res) => {
const { title, author } = req.body;
const resp = await db.collection("books").add({
title: req.body.title,
author: req.body.author,
});
res.sendStatus(200);
});
//accessing the mock data
app.get("/api/stores", function(req, res){
res.json(stores)
})
//querying for a specific title
app.get("/api/stores/:title", function(req, res){
const query = req.params.title;
var result=null;
for(var index = 0; index<stores.length; index++){
var item = stores[index];
if(item.title === query){
result = stores[index];
}
}
res.send(result);
});
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`)
});
我知道上面对express服务器的请求工作正常,因为我已经测试了每个请求,并使用Postman处理Post请求。
现在,对于通过react的前端,我已经在列表中显示了商店(模拟数据)中的标题和作者,并为列表中的每个元素提供了一个按钮,该按钮将用于通过express的POST请求(‘/book/add’)将其保存到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>
);
}
}
有没有人知道用按钮的onClick发出POST请求的方法,以便列表中该元素的相应标题和作者作为文档传递给Firestore集合?
发布于 2021-05-29 22:29:09
这应该是可行的。您需要调用一个函数来在单击按钮时执行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>
);
}
}
https://stackoverflow.com/questions/67752423
复制相似问题