发布到后端后如何获取数据?

时间:2019-07-05 11:08:02

标签: javascript reactjs

我正在尝试将数据发布到后端并在运行函数后检索结果。 post方法有效,但立即调用get无效。


// 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)

}

我希望看到检索到的数据,但是,它不会记录get响应。记录获取响应的唯一方法是在componentwillmount生命周期中,但是如果没有在后端发布URL,则会给我一个URL丢失错误。

3 个答案:

答案 0 :(得分:1)

因为后端与前端之间没有连接,所以无法让节点知道何时应触发结果。也许可以使用WebSocket解决方案来处理它。

答案 1 :(得分:0)

如我所见,除了URL,前端没有任何问题。您正在使用此端点http://localhost:9000/testAPI,但是在后端,您使用的是“ http://localhost:9000/”来获取和发布。因此此“ / testAPI”端点将如何与后端匹配。 您需要这样使用router.post('/ testAPI',())

答案 2 :(得分:0)

感谢您的答复。我已解决此问题...无需获取请求。在获取时添加到获取中的promise已添加到后获取中,并且可以正常工作。将数据变量更改为this.refs.value.value后,应用程序也按预期工作。

相关问题