// pages/index.tsxconstIndexPage=({articles})=>{return(<ul>{articles.map((article,index)=>(<likey={index}>{article.title}</li>))}</ul>);};// we must use `getInitialProps()` to enable SSR correctlyIndexPage.getInitialProps=async({req,query})=>{constisServer=!!req;// and we have to check a process is a server or notletarticles;if(isServer){// if the server side, we can receive data from the server directlyarticles=query.articles;}else{// if the client side, we must fetch data from the API serverarticles=awaithttp.get('api/articles');}// finally, we can use data in the `IndexPage` component like abovereturn{articles,};};
您是否曾想过这样的实现方式?
// server.jsconstexpress=require('express');constapp=express();app.get('/',(req,res)=>{constmessage='Hello World!';res.render('index',{message});});app.listen(3000,()=>{console.log('> Ready on http://localhost:3000');});
// server.jsconstposts=[{id:1,body:'This is a first post.'},{id:2,body:'This is a second post.'},{id:3,body:'This is a last post.'},];app.get('/',(req,res)=>{res.render('index',{posts});});app.get('/posts/:postId',(req,res)=>{const{postId}=req.params;constpost=findById(postId);res.render('post',{post});});
constexpress=require('express');constregister=require('@react-ssr/express/register');constapp=express();(async()=>{// register `.jsx` as a view template engineawaitregister(app);app.get('/',(req,res)=>{constmessage='Hello World!';res.render('index',{message});});app.listen(3000,()=>{console.log('> Ready on http://localhost:3000');});})();
importexpress,{Request,Response}from'express';importregisterfrom'@react-ssr/express/register';constapp=express();(async()=>{// register `.tsx` as a view template engineawaitregister(app);app.get('/',(req:Request,res:Response)=>{constmessage='Hello World!';res.render('index',{message});});app.listen(3000,()=>{console.log('> Ready on http://localhost:3000');});})();
import{NestFactory}from'@nestjs/core';import{NestExpressApplication}from'@nestjs/platform-express';importregisterfrom'@react-ssr/nestjs-express/register';import{AppModule}from'./app.module';(async()=>{constapp=awaitNestFactory.create<NestExpressApplication>(AppModule);// register `.tsx` as a view template engineawaitregister(app);app.listen(3000,async()=>{console.log(`> Ready on http://localhost:3000`);});})();
import{Controller,Get,Render,}from'@nestjs/common';@Controller()exportclassAppController{@Get()@Render('index')// this will render `views/index.tsx`publicshowHome(){constuser={name:'NestJS'};return{user};}}