简体   繁体   English

Puppeteer,ExpressJS,React SSR

[英]Puppeteer, ExpressJS, React SSR

i am trying to achieve Server Side Rendering aka SSR for my react app. 我正在尝试为我的React App实现服务器端渲染(又称SSR)。 I created an express app with puppeteer and got endpoint with following snippets. 我创建了一个带有puppeteer的express应用,并获得了以下代码片段的终结点。

const port = 3003
app.get('*', async (req, res) => {
    try {
        const browser = await puppeteer.launch({headless: true});
        const page = await browser.newPage();
        const local_url = `http://localhost:${port}${req.originalUrl}`;
        await page.goto(local_url, {
            waitUntil: "networkidle0",
        });
        const html = await page.content()
        await browser.close()
        res.send(html);

    } catch(e) {
        console.log(e);
        res.send("ERROR");
    }
});
app.listen(process.env.PORT || port, () => {
    console.log(`Web run ${port}`);
});

I just don't know why this is not working. 我只是不知道为什么这不起作用。 Do I have to run my react app(run on 3000 ) separate and point local_url variable to there? 我是否必须单独运行我的react应用程序(在3000运行)并将local_url变量指向那里? like 喜欢

const local_url = `http://localhost:3000${req.originalUrl}`;

You are in a loop where you are requesting same url over and over. 您处于循环中,一遍又一遍地请求相同的url。 Your react app is in port 3000, and this express app is in port 3003. You can make things a bit easy to read if you seperate them. 您的react应用程序位于端口3000中,而该快速应用程序位于端口3003中。如果您将它们分开,则可以使内容更易于阅读。

You have to run the react server on port 3000 and point to that otherwise it won't know where to browse. 您必须在端口3000上运行react服务器,并指向该服务器,否则它将不知道在何处浏览。

const react_port = 3000;
const server_port = 3003;
const local_url = `http://localhost:${react_port}${req.originalUrl}`;

and vice varsa. 和副瓦尔萨。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM