zoukankan      html  css  js  c++  java
  • [Next] 三.next自定义服务器和路由

    next 服务端渲染

    实际上,next 一直都是执行的服务端渲染.npm start执行的是 next 自带的服务器来运行你的应用.next 是支持自定义服务器的,同时能够支持现有的路由和模式,你可以在此基础上添加一些自己的需求.

    新建/server.js

    const express = require("express");
    const next = require("next");
    const dev = process.env.NODE_ENV !== "production"; //判断是否开发环境
    const app = next({ dev }); //创建一个next的app
    const handle = app.getRequestHandler(); //请求处理
    
    app
      .prepare()
      .then(() => {
        const server = express();
    
        //用来进行简化路径匹配
        server.get("/b/:currentBookId", (req, res) => {
          const actualPage = "/book/[currentBookId]";
          const queryParams = { currentBookId: req.params.currentBookId };
          app.render(req, res, actualPage, queryParams);
        });
    
        server.get("*", (req, res) => {
          return handle(req, res);
        });
    
        server.listen(6776, err => {
          if (err) throw err;
          console.log("> Ready on http://localhost:6776");
        });
      })
      .catch(ex => {
        console.error(ex.stack);
        process.exit(1);
      });
    
    

    其中 app 有 next(opts: object)创建而来

    • dev(bool)是否在开发模式下启动 Next.js-默认 false
    • dir(string)项目所在的位置-默认'.'
    • quiet(bool)隐藏包含服务器信息的错误消息-默认 false
    • conf(object)与您要使用的对象相同 next.config.js-默认{}

    同时修改 package.json 中的配置

    "server:dev": "node server.js",
    "server:start": "NODE_ENV=production node server.js",
    

    解决使用路由隐藏 as 会 404 的问题

    问题在这

    例如

    <Link href={`/book/${item.id}`} as={`/b/${item.id}`}>
    

    然后在npm run dev的情况下,我们使用 next 默认的服务器.页面在使用 as 的时候起了一个缩写路径名称,这种情况在第一次进入是正常匹配的,但是刷新就会 404,原因在于服务器目前并不清楚 b 代表的是什么路径.

    而在 server.js 中就添加了关于 b 的缩写匹配

    //用来进行简化路径匹配
    server.get("/b/:currentBookId", (req, res) => {
      const actualPage = "/book/[currentBookId]";
      const queryParams = { currentBookId: req.params.currentBookId };
      app.render(req, res, actualPage, queryParams);
    });
    

    此时我们npm run server:dev开启自定义服务器,打开页面进入缩写路径,我们刷新发现页面会保留.

    之后npm run dev命令可以抛弃了

    多路径页面

    next 默认会将 pages 下的 js 文件创建出对应的路径.我们起了路由别名,并且通过自定义路由让路由的别名生效.但是我们再次输入 book/[currentBookId],发现依旧可以匹配到同样的页面,造成一个页面拥有的 2 个及以上的路径.这可能会导致 SEO 和 UX 问题

    我们通过设置 useFileSystemPublicRoutes 来禁用默认路由

    // next.config.js
    module.exports = {
      useFileSystemPublicRoutes: false,
    }
    

    重启打开网站,book/[currentBookId]就会直接 404 了.

    useFileSystemPublicRoutes 禁用来自 SSR 的文件名路由.客户端路由仍然可以访问这些路径,需要拦截 popstate来配置客户端也禁用.

    动态 assetPrefix

    有时候我们需要动态路由,比如根据基于请求更改 assetPrefix,这时候我们需要使用 app.setAssetPrefix

    server.get("*", (req, res) => {
        if (req.headers.host === "my-app.com") {
        app.setAssetPrefix("http://cdn.com/myapp");
        } else {
        app.setAssetPrefix("");
        }
        return handle(req, res);
    });
    
    

    禁用 X-Powered-By

    Next.js 将添加 x-powered-by 到请求标头中。这个是由语言解析器或者应用程序框架输出的。这个值的意义用于告知网站是用何种语言或框架编写的。

    直接禁用它

    // next.config.js
    module.exports = {
      poweredByHeader: false,
    }
    

    Doc

  • 相关阅读:
    搜索进阶1、八数码(HDU1043)
    D.迷宫2 (BFS+优先队列)
    小H的询问(线段树)
    B.迷宫(BFS)
    【UVA】10935 Throwing cards away I(STL队列)
    【UVA】10391 Compound Words(STL map)
    【UVA】12100 Printer Queue(STL队列&优先队列)
    【UVA】1596 Bug Hunt(模拟)
    【UVA】201 Squares(模拟)
    【UVA】1595 Symmetry(模拟)
  • 原文地址:https://www.cnblogs.com/mybilibili/p/11716691.html
Copyright © 2011-2022 走看看