谁想创建他们的第一个 UI 应用?我想,如果你正在阅读这篇文章,我假设你也想。在今天的示例中,我将使用一些 JavaScript 和我在之前的文章中演示的 使用 Express 的 API。首先,让我解释一下你即将使用的一些技术。
什么是 React?
React 是一个用于构建用户界面 (UI) 的 JavaScript 库。但是,你需要的不只是 UI 库才能构建功能性的 UI。以下是你即将创建的 JavaScript Web 应用的重要组件
- npx:这个包用于执行 npm 包。
- axios:一个基于 Promise 的 HTTP 客户端,用于浏览器和 node.js。Promise 是 API 端点将提供的值。
- http-proxy-middleware:轻松配置代理中间件。代理是一种中间件,有助于处理从应用程序端点到请求者的来回消息传递。
预配置
如果你还没有看过,请查看我的之前的文章。你将使用该代码作为此 React 应用的一部分。在本例中,你将添加一个服务作为应用程序的一部分使用。作为此应用程序的一部分,你必须使用 npx
包来创建新的文件夹结构和应用程序
$ npx create-react-app count-ui
npx: installed 67 in 7.295s
Creating a new React app in /Users/cherrybomb/count-ui.
Installing packages. This might take a couple of minutes.
Installing react, react-dom, and react-scripts with cra-template...
[...]
Installing template dependencies using npm...
+ @testing-library/jest-dom@5.16.4
+ @testing-library/user-event@13.5.0
+ web-vitals@2.1.4
+ @testing-library/react@13.3.0
added 52 packages from 109 contributors in 9.858s
[...]
Success! Created count-ui at /Users/cherrybomb/count-ui
[...]
We suggest that you begin by typing:
cd count-ui
npm start
正如你所见,npx
命令创建了一个新模板,其中包含文件夹结构、一个很棒的 README
文件和一个 Git 仓库。这是结构
$ cd count-ui/
/Users/cherrybomb/count-ui
$ ls -A -1
.git
.gitignore
README.md
node_modules
package-lock.json
package.json
public
src
此过程还初始化了 Git 仓库并将分支设置为 master,这是一个非常酷的技巧。接下来,安装 npm
包
$ npm install axios http-proxy-middleware
[...]
npm WARN @apideck/better-ajv-errors@0.3.4 requires a peer of ajv@>=8 but none is installed. You must install peer dependencies yourself.
+ http-proxy-middleware@2.0.6
+ axios@0.27.2
added 2 packages from 2 contributors, updated 1 package and audited 1449 packages in 5.886s
现在这些都已设置好,添加你的 services
和 main.js
文件
$ mkdir src/services
src/services
$ touch src/services/main.js
预配置现已完成,现在你可以开始编写代码了。
从头到尾编写一个 UI
现在你已经完成了所有预配置,你可以为你的应用程序组合服务。将以下代码添加到 main.js
文件
import axios from 'axios';
const baseURL = 'http://localhost:5001/api';
export const get = async () => await axios.get(`${baseURL}/`);
export const increment = async () => await axios.post(`${baseURL}/`);
export default {
get,
increment
}
此过程创建一个 JavaScript 文件,该文件与你在我之前的文章中创建的 API 交互。
设置代理
接下来,你必须通过在 src
目录中创建一个新文件来设置代理中间件。
$ touch src/setupProxy.js
使用 setupProxy.js
中的以下代码配置代理
const { createProxyMiddleware } = require('http-proxy-middleware');
module.exports = function(app) {
app.use(
'/api',
createProxyMiddleware({
target: 'http://localhost:5000',
changeOrigin: true,
})
);
};
在此代码中,app.use
函数指定要用作 /api
的服务,以连接到现有的 API 项目。但是,代码中没有定义 api
。这就是代理的用武之地。使用代理,你可以在代理级别定义 api
函数,以便与你的 Express API 交互。此中间件注册两个应用程序之间的请求,因为 UI 和 API 使用具有不同端口的同一主机。它们需要代理来传输内部流量。
JavaScript 导入
在你的基本 src
目录中,你看到原始模板创建了一个 App.js
,你必须将 main.js
(在 services
目录中)添加到 App.js
文件中的导入中。你还需要在第一行导入 React,因为它在项目外部
import React from 'react'
import main from './services/main';
添加渲染函数
现在你有了导入,你必须添加一个渲染函数。在 App.js
的 App() 函数中,在 return 部分之前添加 react 和 count 的定义的第一部分。此部分从 API 获取 count 并将其显示在屏幕上。在 return 函数中,一个按钮提供了递增计数的能力。
function App() {
const [count, setCount] = React.useState(0);
React.useEffect(()=>{
async function fetchCount(){
const newCount = (await main.get()).data.count;
setCount(newCount);
}
fetchCount();
}, [setCount]);
return (
<div className="App">
<header className="App-header">
<h4>
{count}
</h4>
<button onClick={async ()=>{
setCount((await main.increment()).data.count);
}}>
Increment
</button>
</header>
</div>
);
}
要启动和测试应用程序,运行 npm run start
。你应该看到下面的输出。在运行应用程序之前,通过运行 node ./src/index.js
确认你的 API 正在从 Express 应用程序运行。
$ npm run start
> count-ui@0.1.0 start /Users/cherrybomb/count-ui
> react-scripts start
[HPM] Proxy created: / -> http://localhost:5000
(node:71729) [DEP_WEBPACK_DEV_SERVER_ON_AFTER_SETUP_MIDDLEWARE] DeprecationWarning: 'onAfterSetupMiddleware' option is deprecated. Please use the 'setupMiddlewares' option.
(Use `node --trace-deprecation ...` to show where the warning was created)
(node:71729) [DEP_WEBPACK_DEV_SERVER_ON_BEFORE_SETUP_MIDDLEWARE] DeprecationWarning: 'onBeforeSetupMiddleware' option is deprecated. Please use the 'setupMiddlewares' option.
Starting the development server...
一切运行后,在浏览器中打开 localhost:5000
以查看前端有一个漂亮的(虽然不得不承认很小的)页面,带有一个按钮

(Jessica Cherry, CC BY-SA 4.0)
当你按下按钮时会发生什么?(或者,在我的情况下,多次按下按钮。)

(Jessica Cherry, CC BY-SA 4.0)
计数器增加了!
恭喜,你现在有了一个使用你的新 API 的 React 应用程序。
Web 应用和 API
此练习是学习如何使后端和前端协同工作的好方法。值得注意的是,如果你使用两个主机,则不需要本文的代理部分。无论如何,JavaScript 和 React 都是快速、模板化的方式,可以用最少的步骤启动并运行前端。希望你喜欢这次演练。请告诉我们你对学习如何使用 JavaScript 编写代码的想法。
1 条评论