javascript - 如何从我的 express 应用程序获取数据到我的前端组件(在 React 中)?
问题描述
我正在为黑客马拉松开发 MySQL/React/Express/Node 应用程序。我有一条路线,我的合作伙伴向其发出 POST 请求,并且我能够获取 JSON 字段。但是,我想将这些字段发送到我的前端应用程序组件。另外,我不知道什么时候会发出 POST 请求,并且我想将该数据发布到我的服务器后立即将其发送到前端,以便我可以动态更新前端。如何将 JSOMN 数据发送到我的前端,如何继续检查数据是否已发布?这是我的快速应用程序代码,后跟我的应用程序组件:
我尝试将 Express 文件导入我的 React 组件,但这是不可能的。
表达:
var epoch = null;
var accuracy = null;
app.get('/', (_req, res) => {
res.send({"epoch": epoch, "accuracy": accuracy});
})
app.post('/', (req, res) => {
epoch = req.body.epoch;
accuracy = req.body.accuracy;
console.log("Epoch: "+epoch);
console.log("Accuracy: "+accuracy);
res.send("");
})
React 前端应用组件:
import React, { Component } from 'react';
import { BrowserRouter as Router, Route,Switch, Redirect} from 'react-router-dom'
import logo from './logo.svg';
import './App.css';
import 'bootstrap/dist/css/bootstrap.min.css';
import Hello from './Hello.js';
import { Button, Row, Col, Container, Input, Label } from 'reactstrap';
import {
Collapse,
Navbar,
NavbarToggler,
NavbarBrand,
Nav,
NavItem,
NavLink,
UncontrolledDropdown,
DropdownToggle,
DropdownMenu,
DropdownItem } from 'reactstrap';
class App extends Component {
constructor(props){
super(props);
this.state = {
query1: '',
query2: '',
error: '',
epoch: null,
validation_accuracy: null,
isOpen: false,
email: '',
accuracy: ''
}
this.updateInput1 = this.updateInput1.bind(this);
this.updateInput2 = this.updateInput2.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
this.toggle = this.toggle.bind(this);
this.ticker = this.ticker.bind(this);
this.checkEpoch = this.checkEpoch.bind(this);
}
updateInput1(event){
this.setState({query1: event.target.value});
console.log(event.target.value);
}
updateInput2(event){
this.setState({query2: event.target.value});
console.log(event.target.value);
}
checkEpoch(e){
// while(this.state.epoch == null && this.state.epoch < 100){
fetch('http://localhost:4000/', {
method: 'GET',
headers: {
'Content-type': 'application/json',
},
})
.then(res => this.setState({epoch : res.json().epoch, accuracy: res.json().accuracy}))
.then(res => console.log(this.state.epoch))
.then(res => console.log(this.state.accuracy))
.catch((e) => console.log(e));
}
// this.setState({epoch: null});
route_path = () => {
this.props.history.push('/');
}
handleSubmit(e) {
const data = { q1: this.state.query1, q2: this.state.query2 };
fetch('/*remote server*/', {
method: 'POST',
headers: {
'Content-type': 'application/json',
},
body: JSON.stringify(data),
})
.then(res => res.json())
.then(res => console.log(res));
}
render() {
return (
<div className="App">
<Container>
<Row>
<Col><Input placeholder="Class one name." onLoad={this.ticker} className="mt-5" onChange= {this.updateInput1}/></Col>
<Col><Input placeholder= "Class two name." onLoad={this.ticker} className="mt-5" onChange={this.updateInput2}/></Col>
</Row>
<Row>
<Col></Col>
<Col><Button className="mt-5" color='danger' size="lg" onClick={this.handleSubmit, this.checkEpoch}>Go</Button></Col>
<Col></Col>
</Row>
</Container>
<Route path="/hello" component={Hello}/>
</div>
);
}
}```
解决方案
您想要实现的目标可以通过 web-sockets 来完成。
当您进行 HTTP 调用(例如 post 或 get)时,客户端发出请求并接收响应并关闭连接。
而在 Web 套接字中,它们提供客户端和服务器之间的持久连接,双方都可以使用它随时开始发送数据,这正是您想要的。
我建议在您的应用程序中使用socket.io 来开始。
帮助您开始使用 websockets 的文章:
推荐阅读
- scala - 如何从整数值创建枚举
- php - SQL问题'where子句'中的未知列'approved'
- android - 在我的设备上启动时看不到 Cardview
- php - PHP 在 Imagick 中删除 alpha 导致图片损坏
- javascript - 上下文 API 更新状态导致循环请求
- javascript - 请求的模块“./react.js”不提供名为“默认”的导出
- elixir - 如何检索 `iex` 中所有已加载的模块?
- c - NASM x86 核心转储写入内存
- javascript - 如何将 requirejs 文件加载到 creat-react-app
- pytorch - Pytorch 分类交叉熵损失函数行为