Noah Kanyo
Noah Kanyo

Reputation: 550

How to get data after posting to back end?

I am trying to post data to the backend and retrieve the results after running a function. The post method works but immediately calling the get does not.


// Front end

import React, {Component} from 'react';
import './App.css';
import MicrolinkCard from '@microlink/react';

class App extends Component {
  constructor(props) {
    super(props);
    this.state = { 
      practiceText: "",
      description: "",
      value: "",
      image: "",
      title: "",
      desc: "",
      favi: ""
    };
  }

 grabityAPI() {
    return fetch("http://localhost:9000/grabityLink" , { method: 'GET' })
        .then(res =>  res.json())
        .then(res => this.setState({ title: res.title, image: res.image, desc: res.description, favi: res.favicon }))
  }

  callAPI() {
    fetch("http://localhost:9000/testAPI")
        .then(res => res.json())
        .then(res => this.setState({ practiceText: res }));
  }

  componentWillMount() {
    this.callAPI();
  }

  handleChange = async (e) => {
    e.preventDefault();
    this.setState({value: this.refs.value.value})
    const data = { value: this.state.value}
    const options = {
      method: 'POST',
      headers: { "Content-Type": "application/json"},
      body: 
        JSON.stringify(data),
    };
    await fetch("http://localhost:9000/grabityLink", options);  

    // The get response after the post
    const getUrl = await this.grabityAPI();
    return getUrl;
  }


  render(){

    return (
      <div className="App">
        <p className="App-intro">{this.state.practiceText}</p>
        <h2>Enter URL here to compare plugins</h2>
        <input
            type="text"
            ref="value"
            name="url"
            placeholder='Enter URL'
         />
         <button className="btn" onClick={this.handleChange}>Submit</button>
         <hr />
        <div className="Url_box">
            <div className="Url_box1">
              <h3>Microlink Plugin for URL Link Preview</h3>
              <MicrolinkCard url={this.state.value} style={{marginLeft: "10px", width: "500px"}} video size="large"/>
            </div>
            <h2 className="Url_box2">VS.</h2>
            <div className="Url_box1">
              <h3>Grabity Link Preview</h3>
              <div className="grabContainer">
              <img className="imgbox" src={this.state.image} alt="img1"/>
              <div className="descText">
                <p><b>{this.state.title}</b></p>
                <p>{this.state.desc}</p>
                <img src={this.state.favi} alt="img2"/>
              </div>
              </div>
            </div>
        </div>

      </div>
    );
  }
}

export default App;

// Backend

const express = require('express');
const router = express.Router();
const grabity = require("grabity");
const { URL } = require('url');

router.post('/', sharedHandler);
router.get('/', sharedHandler);

async function sharedHandler(req, res, next) {

  const url1 = await req.body.value;
  console.log("log1",url1);
  const it = await grabity.grabIt(url1);
  console.log(it)
  res.json(it)

}

I'd expect to see the data retrieved, but instead, it does not log a get response. The only way it logs the get response is in the componentwillmount lifecycle, but without a Url posted to the backend it gives me a URL missing error.

Upvotes: 0

Views: 416

Answers (3)

Noah Kanyo
Noah Kanyo

Reputation: 550

thanks for the replies. I fixed the issue... There was no need for a get request. The promise added to the fetch on the get fetch was added to the post-fetch and it worked. After changing the data variable fetch to this.refs.value.value as well the application worked as expected.

Upvotes: 0

Varun
Varun

Reputation: 36

As i see there is no problem in frontend except urls. you are hitting this endpoint http://localhost:9000/testAPI but in backend you are using "http://localhost:9000/" this for get and post . so how this '/testAPI' endpoint will match with backend. you need to use like this, router.post('/testAPI', ())

Upvotes: 0

Ehsan Salari
Ehsan Salari

Reputation: 21

because there is no connection between your backend and front end so there is no way to node knows that when should fire the result. maybe could handle it with WebSocket solution.

Upvotes: 1

Related Questions