react中前端和后端通信_如何创建一个React前端和一个Node / Express后端并连接它们...

react中前端和后端通信

by João Henrique

通过JoãoHenrique

如何创建一个React前端和一个Node / Express后端并连接它们 (How to create a React frontend and a Node/Express backend and connect them)

In this article, I’ll walk you through the process of creating a simple React app and connecting it to a simple Node/Express API that we will also be creating.

在本文中,我将引导您完成创建简单的React应用并将其连接到还将要创建的简单Node / Express API的过程。

I won't go into much detail about how to work with any of the technologies I will mention in this tutorial but I will leave links, in case you want to learn more.

我不会详细介绍如何使用本教程中将提到的任何技术,但是如果您想了解更多信息,我将留下链接。

You can find all the code in this repository I made for the tutorial.

您可以在我为教程制作的此存储库中找到所有代码。

The objective here is to give you a practical guide on how to set up and connect the front-end client and the back-end API.

此处的目的是为您提供有关如何设置和连接前端客户端后端API的实用指南。

Before we get our hands dirty, make sure you have Node.js running on your machine.

在弄脏手之前,请确保您的计算机上正在运行Node.js。

创建主项目目录 (Create the Main Project directory)

In your terminal, navigate to a directory where you would like to save your project. Now create a new directory for your project and navigate into it:

在您的终端中,导航到您要保存项目的目录。 现在为您的项目创建一个新目录并导航到其中:

mkdir my_awesome_project
cd my_awesome_project
创建一个React应用 (Create a React App)

This process is really straightforward.

这个过程非常简单。

I will be using Facebook’s create-react-app to… you guessed it, easily create a react app named client:

我将使用Facebook的create-react-app来…您猜对了,轻松创建一个名为client的react应用:

npx create-react-app client
cd client
npm start

Let’s see what I have done:

让我们看看我做了什么:

  1. Used npm’s npx to create a react app and named it client.

    使用npm的npx创建一个react应用并将其命名为client。

  2. cd(change directory) into the client directory.

    cd(更改目录)进入客户端目录。

  3. Started the app.

    启动了应用程序。

In your browser, navigate to http://localhost:3000/.

在浏览器中,导航到http:// localhost:3000 /

If all is ok, you will see the react welcome page. Congratulations! That means you now have a basic React application running on your local machine. Easy right?

如果一切正常,您将看到响应欢迎页面。 恭喜你! 这意味着您现在已经在本地计算机上运行了一个基本的React应用程序。 容易吧?

To stop your react app, just press Ctrl + c in your terminal.

要停止您的react应用,只需在终端中按Ctrl + c

创建一个Express应用 (Create an Express App)

Ok, this will be as straightforward as the previous example. Don’t forget to navigate to your project top folder.

好的,这将与前面的示例一样简单。 不要忘记导航到项目的顶层文件夹。

I will be using the Express Application Generator to quickly create an application skeleton and name it api:

我将使用Express Application Generator快速创建应用程序框架并将其命名为api:

npx express-generator api
cd api
npm install
npm start

Let’s see what I have done:

让我们看看我做了什么:

  1. Used npm’s npx to install express-generator globally.

    使用npm的npx全局安装express-generator。

  2. Used express-generator to create an express app and named it api.

    使用express-generator创建一个Express应用并将其命名为api。

  3. cd into the API directory.

    cd进入API目录。

  4. Installed all dependencies.

    安装所有依赖项。
  5. Started the app.

    启动了应用程序。

In your browser, navigate to http://localhost:3000/.

在浏览器中,导航到http:// localhost:3000 /

If all is ok, you will see the express welcome page. Congratulations! That means you now have a basic Express application running on your local machine. Easy right?

如果一切正常,您将看到快速欢迎页面。 恭喜你! 这意味着您现在已经在本地计算机上运行了基本的Express应用程序。 容易吧?

To stop your react app, just press Ctrl + c in your terminal.

要停止您的react应用,只需在终端中按Ctrl + c

在Express API中配置新路线 (Configuring a new route in the Express API)

Ok, let’s get our hands dirty. Time to open your favorite code editor (I’m using VS Code) and navigate to your project folder.

好吧,让我们动手吧。 是时候打开您喜欢的代码编辑器(我正在使用VS Code )并导航到您的项目文件夹。

If you named the react app as client and the express app as api, you will find two main folders: client and api.

如果您将react应用程序命名为client ,而express应用程序命名为api ,则将找到两个主要文件夹: clientapi。

  1. Inside the API directory, go to bin/www and change the port number on line 15 from 3000 to 9000. We will be running both apps at the same time later on, so doing this will avoid issues. The result should be something like this:

    API目录中,转到bin / www,然后将第15行的端口号从3000更改为9000。稍后我们将同时运行两个应用程序,这样可以避免出现问题。 结果应该是这样的:

2. On api/routes, create a testAPI.js file and paste this code:

2.在api / routes上 ,创建一个testAPI.js文件并粘贴以下代码:

var express = require(“express”);
var router = express.Router();

router.get(“/”, function(req, res, next) {
    res.send(“API is working properly”);
});

module.exports = router;

3. On the api/app.js file, insert a new route on line 24:

3.在api / app.js文件上,在第24行插入新路由:

app.use("/testAPI", testAPIRouter);

4. Ok, you are “telling” express to use this route but, you still have to require it. Let’s do that on line 9:

4.好的,您正在“告诉”快递使用该路线,但是,您仍然需要它。 让我们在第9行上执行此操作:

var testAPIRouter = require("./routes/testAPI");

The only changes are in line 9 and line 25. It should end up something like this:

唯一的变化是在第9行和第25行。它应该以如下形式结束:

5. Congratulations! You have created a new route.

5.恭喜! 您已经创建了一条新路线

If you start your API app (in your terminal, navigate to the API directory and “npm start”), and go to http://localhost:9000/testAPI in your browser, you will see the message: API is working properly.

如果启动API应用程序(在终端中,导航到API目录,然后单击“ npm start” ),然后在浏览器中转到http:// localhost:9000 / testAPI ,您将看到以下消息: API正常运行。

将React Client连接到Express API (Connecting the React Client to the Express API)
  1. On your code editor, let’s work in the client directory. Open app.js file located in my_awesome_project/client/app.js.

    在代码编辑器上,让我们在客户端目录中工作。 打开位于my_awesome_project / client / app.js中的 app.js文件。

  2. Here I will use the Fetch API to retrieve data from the API. Just paste this code after the Class declaration and before the render method:

    在这里,我将使用Fetch API API检索数据 只需在Class声明之后和render方法之前粘贴以下代码:

constructor(props) {
    super(props);
    this.state = { apiResponse: "" };
}

callAPI() {
    fetch("http://localhost:9000/testAPI")
        .then(res => res.text())
        .then(res => this.setState({ apiResponse: res }));
}

componentWillMount() {
    this.callAPI();
}

3. Inside the render method, you will find a <;p> tag. Let’s change it so that it renders the apiResponse:

3.在render方法中,您将找到一个< ; p>标记。 让我们对其进行更改,以使其呈现apiRes响应:

<p className="App-intro">;{this.state.apiResponse}</p>

At the end, this file should look something like this:

最后,该文件应如下所示:

I know!!! This was a bit too much. Copy paste is your friend, but you have to understand what you are doing. Let’s see what I did here:

我知道!!! 这有点太多了。 复制粘贴是您的朋友,但您必须了解自己在做什么。 让我们看看我在这里做了什么:

  1. On lines 6 to 9, we inserted a constructor, that initializes the default state.

    在第6至9行中,我们插入了一个构造函数,用于初始化默认状态。

  2. On lines 11 to 16, we inserted the method callAPI() that will fetch the data from the API and store the response on this.state.apiResponse.

    在第11至16行,我们插入了方法callAPI() ,该方法将从API中获取数据并将响应存储在this.state.apiResponse上。

  3. On lines 18 to 20, we inserted a react lifecycle method called componentDidMount(), that will execute the callAPI() method after the component mounts.

    在第18至20行,我们插入了一个称为componentDidMount()的react生命周期方法该方法将在组件安装后执行callAPI()方法。

  4. Last, on line 29, I used the <;p> tag to display a paragraph on our client page, with the text that we retrieved from the API.

    最后,在第29行,我使用< ; p>标记在客户端页面上显示了一个段落,其中包含我们从API检索到的文本。

有没有搞错!! CORS(What the heck!! CORS ?)

Oh yeah, baby! We are almost done. But if we start both our apps (client and API) and navigate to http://localhost:3000/, you still won't find the expected result displayed on the page. If you open chrome developer tools, you will find why. In the console, you will see this error:

哦耶宝宝! 我们快完成了。 但是,如果我们同时启动我们的应用程序(客户端和API)并导航至http:// localhost:3000 / ,您仍将找不到页面上显示的预期结果。 如果您打开chrome开发人员工具,就会找到原因。 在控制台中,您将看到此错误:

Failed to load http://localhost:9000/testAPI: No ‘Access-Control-Allow-Origin’ header is present on the requested resource. Origin ‘http://localhost:3000' is therefore not allowed access. If an opaque response serves your needs, set the request’s mode to ‘no-cors’ to fetch the resource with CORS disabled.

无法加载http:// localhost:9000 / testAPI :请求的资源上没有“ Access-Control-Allow-Origin”标头。 因此,不允许访问源“ http:// localhost:3000” 。 如果不透明的响应满足您的需求,请将请求的模式设置为“ no-cors”,以在禁用CORS的情况下获取资源。

This is simple to solve. We just have to add CORS to our API to allow cross-origin requests. Let’s do just that. You should check here to find out more about CORS.

这很容易解决。 我们只需要向我们的API添加CORS即可允许跨域请求。 让我们开始吧。 您应该在此处查看有关CORS的更多信息。

  1. In your terminal navigate to the API directory and install the CORS package:

    在您的终端中,导航到API目录并安装CORS软件包:

npm install --save cors

2. On your code editor go to the API directory and open the my_awesome_project/api/app.js file.

2.在代码编辑器上,转到API目录并打开my_awesome_project / api / app.js文件。

3. On line 6 require CORS:

3.第6行要求CORS:

var cors = require("cors");

4. Now on line 18 “tell” express to use CORS:

4.现在在第18行“告诉”表示要使用CORS

app.use(cors());

The API app.js file should end up something like this:

API app.js文件应以如下形式结束:

做得好。 都做完了! (Great Work. It’s all done!!)

Ok! We are all set!

好! 我们都准备好了!

Now start both your apps (client and API), in two different terminals, using the npm start command.

现在,使用npm start命令在两个不同的终端中启动两个应用程序(客户端和API)。

If you navigate to http://localhost:3000/ in your browser you should find something like this:

如果您在浏览器中导航到http:// localhost:3000 / ,则应该找到类似以下内容的内容:

Of course, this project as it is won’t do much, but is the start of a Full Stack Application. You can find all the code in this repository that I’ve created for the tutorial.

当然,这个项目不会做很多,但是是Full Stack Application的开始。 您可以在该存储库中找到我为教程创建的所有代码。

Next, I will work on some complementary tutorials, like how to connect this to a MongoDB database and even, how to run it all inside Docker containers.

接下来,我将研究一些补充教程,例如如何将其连接到MongoDB数据库,甚至如何在Docker容器中运行它们。

As a good friend of mine says:

正如我的一个好朋友所说:

Be Strong and Code On!!!
坚强并编码!!!

…and don't forget to be awesome today ;)

…别忘了今天变得很棒;)

翻译自: https://www.freecodecamp.org/news/create-a-react-frontend-a-node-express-backend-and-connect-them-together-c5798926047c/

react中前端和后端通信

  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值