如何添加功能以便在单击提交按钮时
我的应用程序状态中的所有内容都会传递到后端 - 比如说
到文本文件,或在 json 文件中。
您可以使用 Axios 或 Fetch API 请求数据以在您的应用程序中使用。您可以使用两种最流行的方法使用 REST API,即 Axios(基于 Promise 的 HTTP 客户端)和 Fetch API(浏览器内置的 Web API)。
fetch() API 是一种用于从服务器或 API 端点获取资源的内置 JavaScript 方法。类似于 XMLHttpRequest
Axios 是一个易于使用的基于 Promise 的 HTTP 客户端,适用于浏览器和 node.js。由于 Axios 是基于 Promise 的,我们可以利用 async 和 await 来获得更具可读性和异步性的代码。借助 Axios,我们可以拦截和取消请求,它还具有内置功能,可提供客户端保护,防止跨站请求伪造。
想了解更多可以参考this
- 以上这两种方法,都可以用来将你前端的数据提交到后端,这样数据就存储到后端,然后你就可以根据自己的需求对其进行多种操作了。
您可以参考多个博客和文档以了解更多信息:
Use axios to fetch data from an api in ReactJS
Fetch API for POST Request
Axios
Difference between Axios and Fetch API
最近,我还创建了一个应用程序,其中我正在将 React 与 SpringBoot 应用程序集成。
在此应用程序中。我已经使用 axios 设置了路由器和路由,创建并提交了表单,称为 GET、POST、PUT、DELETE 请求(也使用 fetch API 完成)。
submitBook= event =>{
event.preventDefault();
const book = {
title: this.state.title,
author: this.state.author,
coverphotoURL: this.state.coverphotoURL,
isbnNumber: this.state.isbnNumber,
price: this.state.price,
language: this.state.language
};
const headers = new Headers();
headers.append("Content-Type", "application/json");
fetch("http://localhost:8080/rest/books",{
method:"POST",
body:JSON.stringify(book),
headers
})
.then(response => response.json())
.then((book) => {
if(book){
this.setState({"show":true, "method":"post"});
setTimeout(() => this.setState({"show":false}),3000);
}
else{
this.setState({"show":false});
}});
this.setState(this.initialState);
};
查看完整代码,可以参考我的Github Repository