具有自定义Express服务器的Next.js重新呈现所有自定义路由

时间:2018-07-24 21:00:31

标签: javascript reactjs express next.js

我已经在server.js中设置了一个自定义快递服务器,例如Next.js的文档给出了example of,但是,每次导航到那里定义的任何动态路由时,都会重新渲染的应用程序,其中包含包含我的样式的,会导致大量未样式化内容的闪烁。有没有办法确保动态路由不会触发重新渲染?

这是我的server.js文件:

const express = require("express");
const next = require("next");

const dev = process.env.NODE_ENV !== "production";
const app = next({ dev });
const handle = app.getRequestHandler();

app
    .prepare()
    .then(() => {
        const server = express();

        server.get("/press/:slug", (req, res) => {
            const actualPage = "/press";
            const queryParams = { slug: req.params.slug, apiRoute: "press" };
            return app.render(req, res, actualPage, queryParams);
        });

        server.get("/locations/:slug", (req, res) => {
            const actualPage = "/locations/location";
            const queryParams = { slug: req.params.slug, apiRoute: "location" };
            return app.render(req, res, actualPage, queryParams);
        });

        server.get("/insights/:slug", (req, res) => {
            const actualPage = "/insights/insight";
            const queryParams = { slug: req.params.slug, apiRoute: "insight" };
            return app.render(req, res, actualPage, queryParams);
        });

        // server.get("/_preview/:id/:wpnonce", (req, res) => {
        //     const actualPage = "/preview";
        //     const queryParams = { id: req.params.id, wpnonce: req.params.wpnonce };
        //     app.render(req, res, actualPage, queryParams);
        // });

        const robotsOptions = {
            root: __dirname + '/static/',
            headers: {
                'Content-Type': 'text/plain;charset=UTF-8',
            }
        };
        server.get('/robots.txt', (req, res) => (
            res.status(200).sendFile('robots.txt', robotsOptions)
        ));

        const sitemapOptions = {
            root: __dirname + '/static/',
            headers: {
                'Content-Type': 'text/xml;charset=UTF-8',
            }
        };
        server.get('/sitemap.xml', (req, res) => (
            res.status(200).sendFile('sitemap.xml', sitemapOptions)
        ));

        server.get("*", (req, res) => {
            return handle(req, res);
        });

        server.listen(3000, err => {
            if (err) throw err;
            console.log("> Ready on http://localhost:3000");
        });
    })
    .catch(ex => {
        console.error(ex.stack);
        process.exit(1);
    });

1 个答案:

答案 0 :(得分:-1)

您的href应为as属性。根据文档重建href属性 看看nextjs文档 https://nextjs.org/docs#with-link