node.js - 如何从后端快速服务器获取数据到前端反应应用程序,反之亦然
问题描述
我有一个简单的快递后端
const express = require("express");
const app = express();
var array = [1,2,3,4,5]
app.get("/", function(req, res){
res.send("this is backend of application");
})
app.listen(5000, ()=> console.log("listening on 5000"));
我还有一个由 create-react-app 创建的简单前端
import React from "react";
import ReactDOM from "react-dom";
import App from "./app"
ReactDOM.render(
<div>
<App />
</div>, document.getElementById("root"));
现在我的问题是如何将“数组”从后端文件获取到我的前端反应文件和。反之亦然??
解决方案
在您的组件中创建一个方法并使用内置的 fetch API。您也可以使用axios
.
componentDidMount() {
fetch("http://localhost:5000/")
.then(res => res.json())
.then(
(result) => {
// set state here
console.log(result);
},
// Note: it's important to handle errors here
// instead of a catch() block so that we don't swallow
// exceptions from actual bugs in components.
(error) => {
console.log(error);
}
)
}
在这里查看更多详情。
在节点端进行以下更改:
const express = require("express");
const app = express();
var array = [1,2,3,4,5]
app.get("/", function(req, res){
res.send({message: "this is backend of application", data: array});
})
app.listen(5000, ()=> console.log("listening on 5000"));
注意:如果你按照这篇文章创建一个带有 Node 后端的 React 应用程序将会很容易。
推荐阅读
- html - 在 HTML/CSS 中覆盖浏览器默认字体 - 但不是代码字体?
- ios - 创建可重用的 UIView 子类 - 遇到大小问题
- swift - 如何快速执行一个函数 5 秒
- android - Android:运行测试用例时:无法确定任务':app:compileDebugAndroidTestJavaWithJavac'的依赖关系
- python - 如何将 self 参数传递给 python cProfile
- reactjs - 应用 find() 时获得 2 个渲染而不是 1 个渲染
- reactjs - React 构建文件不适用于共享主机
- r - r 中具有平均值和 sd 的频率表,每行有多个案例
- c# - WinForms txtTextbox_MouseEnter 触发表单上的所有文本框
- javascript - 如何删除字符串中任何语言的所有非字母字符?