gpt4 book ai didi

node.js - 在快速路线上渲染 react 组件

转载 作者:太空宇宙 更新时间:2023-11-04 01:50:54 25 4
gpt4 key购买 nike

我有一个使用 Express 服务器和 create-react-app 前端的应用程序。结构看起来像这样。 (不包括结构中的所有文件 - 仅包括重要的文件)

Client-
build
etc
public
src-
assets
components-
landing-
landing.js
github-
github.js
steam-
steam.js
App.js
index.js
routes-
routes.js
index.js

我的index.js文件正在启动express服务器,如下所示-

const express = require( 'express' );

const app = express();
const PORT = process.env.PORT || 5000;

require('./routes/routes')( app );

app.use( express.static( 'client/build' ));

app.listen( PORT, () => {
console.log( "Server is running on port 5000 " );
});

服务器端的路由文件如下-

module.exports = ( app ) => {

app.get( '/', ( req, res ) => {
console.log("Hello");
res.send( "Hello" );
});

app.get( '/steam', ( req, res ) => {
res.send( "Place for Steam!!");
});

app.get( '/github', ( req, res ) => {
res.send("Place for Github!!");
});
}

我的app.js 文件

class App extends Component {
render() {
return (
<div className="App">
<BrowserRouter>
<div className="container">
<Route path="/" component={ Landing }/>
<Route path="/steam" exact component={ Steam } />
<Route path="/github" exact component={ Github } />
</div>
</BrowserRouter>
</div>

);
}
}

export default App;

在我的客户端,我主要关心的landing.js文件如下。

class Landing extends Component{
render(){
return(
<div className="container">
<div className="row">
<div className="col-md-6">
<div className="bg">
<img src="https://www.bleepstatic.com/content/hl-images/2016/12/23/Steam-Logo.jpg" alt="" />
<div className="overlay">
<a href="/steam" className="custombutton custombutton-white custombutton-big">Steam Info</a>
</div>
</div>
</div>
<div className="col-md-6">
<div className="bg">
<img src="https://linuxforlyf.files.wordpress.com/2017/10/github-universe1.jpg" alt="" />
<div className="overlay">
<a href="/github" className="custombutton custombutton-white custombutton-big">Github Info</a>
</div>
</div>
</div>
</div>
</div>
)
}
}

export default Landing;

在上面的组件中,我关心的是 a 标签,它导致 /steam/github 快速路由,这是故意的,因为我想重新加载页面,并且在页面上我只获取 res.send 数据,这是有道理的,因为这是一条快速路由。但我想在 /steam 路由上渲染我的 steam 组件。 (与 github 相同)。我希望我的 App.js 中的 BrowserRouter 能够根据路由更改组件,但事实并非如此。我只是获取 express 数据。如何在 express '/steam' 路由上渲染我的 Steam React 组件。显然我正在以奇怪的方式混合服务器和客户端。

最佳答案

只需对所有后端路由使用 res.render('index'); 即可。

这里我们正在使用 React 构建一个单页面应用程序,这意味着只有一个入口文件(只有一个 html 文件,通常是 index.html),页面呈现方式有所不同,因为我们的 js 代码检查 url 并决定显示什么(使用哪个前端路由)。它们都是在浏览器收到 html 文件以及包含的 js/css 文件后发生的。当收到页面请求时,后端要做的就是发送相同的 html 文件(以及浏览器解析 html 后的 js/css 文件)。当然对于data/xhr请求和无效请求,我们需要相应地发送数据和404.html

关于node.js - 在快速路线上渲染 react 组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49724765/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com