Wil*_*ain 6 reactjs react-router
我的 ReactJS 应用程序在http://localhost:3000/中运行。我将以下表单数据作为 POST 请求接收到我的 React 页面
<form action="http://localhost:3000/" method="post">
Employee Id: <input type="text" name="eid"><br>
Department Id: <input type="text" name="did"><br>
<input type="submit" value="Submit">
</form>
Run Code Online (Sandbox Code Playgroud)
我的 React 应用程序应该能够处理此 POST 请求并呈现 UI,如下所示
<h1>{eid}</h1>
<h1>{did}</h1>
Run Code Online (Sandbox Code Playgroud)
我能够使用 React 路由器处理 GET 请求,但很难处理 POST 请求。我怎样才能实现这个目标?
如果你的 React 应用程序是静态的(不是服务器端渲染的),这是不可能的。当你向你的react应用程序发送一些POST请求时,nginx(或其他服务器)将不允许这种操作(你不能发布到静态文件)即使你绕过该限制,react脚本也不会从你的POST请求中获取任何数据,因为 nginx 会处理你的请求并返回一个带有 React 脚本的 html 给你
Pio*_*Żak -3
首先,您可能需要一些理论观点:
https://pusher.com/tutorials/consume-restful-api-react
https://www.robinwieruch.de/react-hooks-fetch-data
要从 api (GET)下载数据- 您不直接以表单形式执行 - 您只需使用ComponentDidMount或UseEffect。
componentDidMount() {
fetch(ApiURL)
.then(res => res.json())
.then(res => this.setState({ planets: res }))
.catch(() => this.setState({ hasErrors: true }));
}
Run Code Online (Sandbox Code Playgroud)
useEffect(async () => {
const result = await axios(
ApiURL,
);
setData(result.data);
});
Run Code Online (Sandbox Code Playgroud)
要将数据发送到 api (POST) - 这很复杂 - 您需要有关客户端-服务器通信的信息
直接来自 React 文档:
fetch('https://mywebsite.com/endpoint/', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
firstParam: 'yourValue',
secondParam: 'yourOtherValue',
})
})
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
12386 次 |
| 最近记录: |