React 全栈
“React Fullstack”是一系列用于创建基于 React 的全栈应用程序的库!
“React Fullstack”的主要包是
- 全栈或
npm i @react-fullstack/fullstack - Express 服务器
npm i @react-fullstack/server-express
所以……我今天早上醒来时突然有了个想法——“用 React 创建可响应的 Node HTTP/S 服务器可能会很有趣”,于是我坐下来开始工作,现在经过 4-5 个小时的工作,我有一个消息要宣布——现在你可以使用 Express.js 的 React warp 创建可响应的 HTTP/S 服务器了。
注意:如果您对阅读本文不感兴趣,只想使用 React 创建 HTTP/s 服务器,这完全没问题,您可以立即使用npm install @react-express/server或安装精简版,您可以在react-express githubnpm install @react-express/server-core上找到示例用法。
React 的魅力在于一切皆有状态且可响应,更不用说它极其优美的语法了。
如果你还不熟悉 React,请务必了解一下,它是用户基数最大的 Web 库/框架,而且在我看来也是最好的 :)
所以……在我看来,React 的所有优势(有状态、可响应、简洁的语法、组件化等等)也可以应用到服务器端。Express
服务器很棒,但我觉得它们过于静态,而 React 可以改变这一点!
首先,让我们在服务器上安装“@react-express/server”,我们可以通过npm install @react-express/server在项目中运行以下命令来完成此操作。
既然我们要使用 JSX,那就确保在项目中启用 JSX。你可以使用 Bable和TypeScript 来学习如何操作。
现在开始编写代码!如果我们想在项目中挂载一个 HTTP 服务器,我们需要在代码中添加以下几行。
import React from "react";
import { Render, Server, Route } from "@react-express/server"; // import the Render method and all the simple routing components
Render(
<Server listen port={2345 /* the port we want to listen on */}>
<Route path={"/" /* the path we cant to handle requests from */} get={(req, res) => res.send("hello world") /* send "hellow world" response to every request at "http://localhost:2345/" */} />
</Server>
就这样,我们创建了一个 hello-world HTTP/s 服务器。
更高级的路由:
...
import {..., Router } from "@react-express/server"; // import the Router component
const posts = ["hello", "world 🗺"];
// applay middlewares
const use = (app) => {
app.use(express.json(), express.urlencoded({ extended: true }));
};
Render(
<Server listen port={2345}>
<Router reference={use} path="/posts">
<Route path="/" get={(req, res) => res.send(posts) /* get all posts*/} />
<Route
path="/:id"
get={(req, res) => res.send(posts[req.params.id])}
delete={(req, res) => posts[req.params.id] = "empty"}
/>
</Router>
</Server>
仅仅因为现在可以做到——将 React 组件渲染到客户端:
...
import {..., ReactRoute } from "@react-express/server"; // import the Render method and all the simple routing components
const posts = ["hey", "bey", "hello", "world 🗺"];
// applay middlewares
...
Render(
<Server listen port={2345 /* the port we want to listen on */}>
<Router reference={use} path="/posts">
<ReactRoute >{
() => (
{posts.map((post, index) => (
<li
style={{
color: `#${Math.floor(Math.random() *16777215).toString(16)}`,
}}
key={index}
>
<h1>{post}</h1>
</li>
))}
)}
</ReactRoute>
<Route
path="/:id"
get={(req, res) => res.send(posts[req.params.id])}
delete={(req, res) => posts[req.params.id] = "empty"}
/>
</Router>
</Server>
如果您也对使用 React 编写服务器的想法很感兴趣,欢迎查看以下代码库:
“React Fullstack”是一系列用于创建基于 React 的全栈应用程序的库!
“React Fullstack”的主要包是
npm i @react-fullstack/fullstacknpm i @react-fullstack/server-express代码库很小也很简单,所以如果你想贡献代码,欢迎随时提交 pull request :)
文章来源:https://dev.to/shmuelhizmi/create-http-servers-using-react-4k1o