简体   繁体   中英

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. I have a route to which my partner makes a POST request and I'm able to get the JSON fields. 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. How can I send the JSOMN data to my frontend, and how can I keep checking whether the data has been posted? 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:

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:

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.

When you do a HTTP call (say a post or get) client makes a request receives a response and the connection is closed.

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.

I recommend using socket.io in your application to get started.

Articles to get you started with websockets:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM