简体   繁体   English

如何从express.js发送数据以在没有API的情况下做出反应?

[英]how to send data from express.js to react without API?

I want to create a Multi Page APP using react and express. 我想使用react和express创建一个Multi Page APP。

I am confused about how to retrieve data sent by the express into react without using the API. 我对如何在不使用API​​的情况下如何检索快递发送的数据感到困惑。

I wonder if react can retrieve the data stored in html props sent by express? 我想知道react是否可以检索express发送的html属性中存储的数据? maybe this question is a little weird. 也许这个问题有点奇怪。 actually I have never created a website with just an express. 实际上,我从未创建过一个快递网站。 I always use react and retrieve data through the API and create a Single Page App. 我总是使用react和通过API检索数据并创建一个Single Page App。

is there any way to do this? 有什么办法吗?

React and express are playing two different roles. React和Express扮演着两个不同的角色。 React Is your front end. React是您的前端。 Express is the backend. Express是后端。 Those are logically separated layers. 这些是逻辑上分离的层。 The preferred way to load data from backend to frontend is through API calls. 将数据从后端加载到前端的首选方法是通过API调用。

I wonder if react can retrieve the data stored in html props sent by express?

Yes it can. 是的,它可以。 I'm not sure what you mean by "html props", but you can store the needed data as data-attributes when sending back the html to the front-end, and then pull it out of the DOM like so ( https://developer.mozilla.org/en-US/docs/Learn/HTML/Howto/Use_data_attributes ). 我不确定“ html道具”是什么意思,但是当将html发送回前端时,您可以将所需的数据存储为数据属性,然后像这样将其从DOM中拉出( https:/ /developer.mozilla.org/zh-CN/docs/Learn/HTML/Howto/Use_data_attributes )。

Depending on how you plan to use it, you can just pull that data out for one-time usage or push it into your state. 根据您打算如何使用它,您可以只提取一次数据或将其推入您的状态。

The first way I could think it is to use the parameters in url. 我认为的第一种方法是在url中使用参数。

For example, if your website has url like http://localhost/ and you will use url http://localhost/api/data? 例如,如果您的网站具有类似http://localhost/ URL,而您将使用URL http://localhost/api/data? to receive data from express.js. 从express.js接收数据。

Then in your express.js , after getting request from your react, you can use: 然后在您的express.js ,在收到您的响应请求后,可以使用:

res.redirect( http://localhost/api/${encodeURIComponent(JSON.stringify(data))}) res.redirect( http://localhost/api/${encodeURIComponent(JSON.stringify(data))})

where res is the response object and data is the data you want to send to data, which is assumed to be an object. 其中res是响应对象, data是要发送到数据的数据(假定是对象)。

In your react , you can retrieve your data with the following steps: - implement a component and set /api/data? 在您的react ,可以通过以下步骤检索数据:-实现组件并设置/api/data? as the route of this component; 作为此组件的路线; - in the component, retrieve the data as JSON.parse(decodeURIComponent(this.props.match.params.data)) -在组件中,将数据检索为JSON.parse(decodeURIComponent(this.props.match.params.data))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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