react连接后端_如何将您的React应用连接到相同来源的后端

react连接后端

I think the single most used way to start a React app is using create-react-app. It’s very convenient.

我认为启动React应用程序最常用的方法是使用create-react-app 。 非常方便

One problem you might stumble upon is how to connect it to a backend you already have, or one you might want to create.

您可能会遇到的一个问题是如何将其连接到您已经拥有的后端,或者您可能想创建一个。

开发中 (In development)

When developing the app you want to take advantage of hot reloading and all the other convenient features of create-react-app. How can you combine that with a backend without having to use CORS on the server and worry about ports?

在开发应用程序时,您想利用热重载和create-react-app的所有其他便利功能。 您如何将其与后端结合而不必在服务器上使用CORS并担心端口?

I am going to provide an example using Express in the post, but this applies to any other framework.

我将在帖子中提供一个使用Express的示例,但这适用于任何其他框架。

Assuming you are testing this, let’s create a React app:

假设您正在测试,让我们创建一个React应用程序:

npx create-react-app testing

then

然后

cd testing

Now create a simple Express server in a server.js file, which you can add anywhere you want. It can even be in a separate folder altogether.

现在,在server.js文件中创建一个简单的Express服务器,您可以在任意位置添加它。 它甚至可以完全放在单独的文件夹中。

If you choose to add this file inside the create-react-app application code, run:

如果您选择将此文件添加到create-react-app应用程序代码中,请运行:

npm install express

And we’re ready to go. Add this simple Express setup:

我们已经准备好出发了。 添加此简单的Express设置:

const express = require('express');
const app = express();

app.get('/hey', (req, res) => res.send('ho!'))

app.listen(8080)

Crucial point here: open the package.json file and add this line somewhere:

这里的关键点:打开package.json文件,并将此行添加到某处:

"proxy": "http://localhost:8080"

This tells React to proxy API requests to the Node.js server built with Express.

这告诉React将代理API请求发送给使用Express构建的Node.js服务器。

Now run this Node process using node server.js. In another window you start the CRA app using npm start.

现在,使用node server.js运行此Node进程。 在另一个窗口中,使用npm start CRA应用npm start

When the browser opens on port 3000 (by default), open the DevTools and run:

当浏览器在端口3000(默认)上打开时,打开DevTools并运行:

fetch('/hey')

If you check the network panel, you should have a successful response with the ho! message.

如果检查网络面板,则应该对ho!作出成功的响应ho! 信息。

在生产中 (In production)

In production, you are going to run npm run build when you are ready to deploy and we will use the Express server to serve those static files.

在生产环境中,准备部署时将运行npm run build ,我们将使用Express服务器来提供这些静态文件。

The whole proxy thing is now useless (and will not work in production, too - it’s meant to ease development). Which means you can leave it in the package.json file if you find it convenient.

整个代理服务器现在已经无用了(并且在生产环境中也将不起作用,这是为了简化开发)。 这意味着,如果发现方便,可以将其保留在package.json文件中。

In the code below, we require the path built-in Node module and we tell the app to serve the static build of the React app:

在下面的代码中,我们需要内置path的Node模块,并告诉该应用提供React应用的静态构建:

const express = require('express')
const path = require('path')
const app = express()

app.use(express.static(path.join(__dirname, 'build')))

app.get('/ping', (req, res) => {
  return res.send('pong')
})

app.get('/', (req, res) => {
  res.sendFile(path.join(__dirname, 'build', 'index.html'))
})

app.listen(8080)

翻译自: https://flaviocopes.com/how-to-serve-react-from-same-origin/

react连接后端

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
React中渲染后端数据,你可以使用以下步骤: 1.后端数据获取到前端,可以使用Fetch、Axios或其他HTTP库发送GET请求来数据。确保你已经正确地配置了后端API的URL和参数。 2. 在React组件中创建一个状态(state)来存储后端数据。你可以使用useState钩子函数或者类组件的state来实现。 3. 在组件加载或数据更新时,使用useEffect钩子函数(函数组件)或componentDidMount(类组件)发送请求并更新状态。 4. 在组件的渲染函数中,根据状态中的数据渲染UI。你可以使用条件渲染、循环渲染或者其他逻辑来展示后端数据。 下面是一个使用函数组件和useState钩子函数的示例: ```javascript import React, { useState, useEffect } from 'react'; function App() { const [data, setData] = useState([]); useEffect(() => { fetch('your-backend-api-url') .then(response => response.json()) .then(data => setData(data)); }, []); return ( <div> {data.map(item => ( <div key={item.id}> <h3>{item.title}</h3> <p>{item.description}</p> </div> ))} </div> ); } export default App; ``` 在上面的示例中,我们使用了useState和useEffect钩子函数来获取后端数据,并将其存储在名为data的状态中。然后,我们在渲染函数中使用map函数遍历data数组,并将每个元素渲染为一个包含标题和描述的div。 请根据你的具体需求和后端API的返回数据结构进行适当的调整。希望这能帮助到你!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值