gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 23:22:12 25 4
gpt4 key购买 nike

我正在尝试将数据发布到后端并在运行函数后检索结果。 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)

}

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

最佳答案

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

关于javascript - 发布到后端后如何获取数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56901884/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com