React 中的 Express!React 后端!什么?!🤯
嘿!又一个 React 的疯狂想法实现了
主意
很久以前,当我在研究React 自定义渲染器时,我就萌生了一个疯狂的想法,想把它用在 Node.js 的服务器/后端上。最终,我决定尝试一下。
免责声明⚠️
- 这不是完全准备好的解决方案(正在进行中)
- 不要将其用于生产
- 是的,我了解可扩展性、架构等等。这只是一个实验项目。放心吧🛀
它是如何工作的?
它与 express.js 框架配合使用,运行 Node.js 服务器。自定义渲染器基于 React Components 构建 express 结构的应用程序。
它看起来怎么样?
基本代码示例
import React from "react";
import ReactExpress from "./renderer";
const HomePage = () => <h1>Welcome to home page</h1>;
const AboutPage = () => <><h1>About Company</h1><p>Bla bla</p></>;
const ExpressApp = () => (
<app port={8080}>
<router path="/">
<get content={<HomePage />} />
<get path="*" content="Not Found" status={404} />
</router>
<router path="/company">
<get path="/about" content={<AboutPage />} />
</router>
<router path="/api">
<post path="/status" content={{ msg: "It is okay, bro" }} />
</router>
</app>
);
ReactExpress.render(<ExpressApp />);
实例
有适用于 express.js 实例的组件,例如router, static, get, post and etc.
成分
<app />
- 应用程序实例(属性:端口)
<static />
- 静态路由(道具:publicPath,path,options)
<router />
- 路由器提供商(道具:路径)
<get />, <post /> and ...
- 路由组件(道具:路径、内容、处理程序、状态)
...仍在进行中
让我们深入了解路由组件
我们的路线组件是<get />, <post />, <delete /> and etc.
它们具有相同的结构。
例子:
// Response json
<get path="/status" content={{ msg: "I\'m okay" }} />
// Response SSR React-Component
<get path="/homepage" content={() => <h1>Welcome to home page</h1>} />
// Response error
<get path="/not-found" content="Page not found" status={404} />
// Response with handler
<get path="/posts/:id" handler={(req,res) => res.send(`id is ${req.params.id}`)} />
// The same for all methods
<post path="/posts/:id" handler={(req,res) => res.send(`id is ${req.params.id}`)} />
React API
目前可以使用 React Context API。
例如,有一种获取处理程序的请求和响应参数的方法。它在项目演示中使用
import { context } from "../../context";
export const TopNav = () => {
const { req, res } = useContext(context);
return (
<TopWrapper currentPath={req.originalUrl}>
<Logo href="/"> </Logo>
<NavItem href="/">Home</NavItem>
<NavItem href="/components">Components</NavItem>
<NavItem href="https://github.com/gigantz/react-xpress">Github</NavItem>
</TopWrapper>
);
};
什么是规划?
我正在努力改进它,尽管在实际应用中使用这种渲染器可能不太好。但如果能有贡献者来改进它的 DX 就太好了。
组件的未来
我有一个计划让它变成这样
// Add components from the lib
import {Router, Middleware, Res, Get, Post} from 'react-xpress';
// Make more component based structure
<Get path="/not-found">
<Res.Status code={404} />
<Res.Content text="Page is not found" />
</Get>
// Using Middlewares
<Get path="/user">
<Middleware handler={checkToken}>
<Res.Status code={401} />
<Res.Content json={{ status: 401, msg: "No access" }} />
</Middleware>
<Res.Content>
<UserPage />
</Res.Content>
</Get>
...
还有更多疯狂的想法正在进行中。
演示
这是一个工作原型 - http://react-xpress-demo.herokuapp.com/
它的 Github repo - https://github.com/gigantz/react-xpress
结论
欢迎随时联系我并贡献项目。项目正在开发中,请关注我的动态以获取更新。希望我们能尽快推出更好的产品。现在您可以轻松克隆代码库并试用。
我还计划写一篇关于 React 自定义渲染器的文章。希望你们喜欢这种实验。
干杯🎉✨,
Orkhan Jafarov