简体   繁体   English

如何从我的 express 应用程序获取数据到我的前端组件(在 React 中)?

[英]How can I get data from my express app to my component in the frontend(which is in React)?

I'm working on a MySQL/React/Express/Node app for a hackathon.我正在为黑客马拉松开发 MySQL/React/Express/Node 应用程序。 I have a route to which my partner makes a POST request and I'm able to get the JSON fields.我有一条路线,我的合作伙伴向其发出 POST 请求,并且我能够获取 JSON 字段。 However, I want to send those fields to my frontend App Component.但是,我想将这些字段发送到我的前端应用程序组件。 Also, I do not know when the POST request will be made and I want to send that data to the front end as soon as its POSTED to my server, so that I can dynamically update the frontend.此外,我不知道何时会发出 POST 请求,并且我想将该数据发布到我的服务器后立即将其发送到前端,以便我可以动态更新前端。 How can I send the JSOMN data to my frontend, and how can I keep checking whether the data has been posted?如何将 JSOMN 数据发送到我的前端,如何继续检查数据是否已发布? Here's my code for the express app followed by my App component:这是我的快速应用程序代码,后跟我的应用程序组件:

I've tried importing the Express file into my React component, but that's not possible.我尝试将 Express 文件导入我的 React 组件,但这是不可能的。

Express:表达:

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 Frontend App Component: 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>
        );
}
}```

What you are trying to achieve can be done by web-sockets.您想要实现的目标可以通过 web-sockets 来完成。

When you do a HTTP call (say a post or get) client makes a request receives a response and the connection is closed.当您执行 HTTP 调用(例如 post 或 get)时,客户端发出请求接收响应并关闭连接。

Whereas in web sockets they provide a persistent connection between a client and server that both parties can use to start sending data at any time, just what you want.而在 web sockets 中,它们提供了客户端和服务器之间的持久连接,双方都可以使用它随时开始发送数据,这正是您想要的。

I recommend using socket.io in your application to get started.我建议在您的应用程序中使用socket.io来开始。

Articles to get you started with websockets:帮助您开始使用 websockets 的文章:

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何将数据发送到Express中的前端js文件 - How can I send data to my frontend js files in express 我如何让我的快递服务器从我的React客户端应用程序获取请求? - How do I get my express server to GET a request from my React client app? 如何在React组件中从Express端点获取数据? - How do I get data from Express endpoint in a React component? 如何从 Firebase 获取数据到我的 React 应用程序中 - How can I fetch data from Firebase into my React App 如何从本地文件获取数据到我的 React 应用程序中? - How can I get data from a local file into my React app? 如何将唯一标识符从我的 express 后端服务器传递到我的前端 reactjs 以显示在我的 web 应用程序中? - How can I pass a unique identifier from my express backend server to my frontend reactjs to be displayed in my web application? 当通过 http 响应发送到我的前端时,如何从我的后端获取 oauth_token 数据? - How can I get the oauth_token data from my backend when it's sent via a http response to my frontend? 为什么我的 React-Express 应用程序无法从 express 后端获取和显示数据? - Why my React-Express app can not fetch and display data from express backend? 无法从节点/快递获取成功响应数据/状态到我的客户端应用程序(反应):“referenceerror response is not defined” - can't get success response data/status from node/express to my client app(react): "referenceerror response is not defined" 如何让我的 React 组件在退出 HTML 时呈现 - How can I get my React component to render on exiting HTML
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM