Next JS 导出到静态 HTML 刷新时始终重定向到主页“/”

Yve*_*aga 3 reactjs next.js

我正在使用NextJSReact创建一个博客应用程序。由于本教程,我已经了解了基础知识

所以我尝试实现博客应用程序。当我尝试在开发模式下测试它时,yarn dev路由很好。但是如果我构建它yarn build并导出为静态 HTML yarn export。当我点击链接时,路由会丢失,它会出现在正确的页面上,但是当我刷新浏览器时,它总是带我回到页面/

为什么会发生这种情况?

这是示例代码

header.js 组件

import Link from 'next/link'

const linkStyle = {
  marginRight: 15
}

export default function Header() {
  return (
    <div>
      <Link href="/">
        <a style={linkStyle}>Home</a>
      </Link>
      <Link href="/about">
        <a style={linkStyle}>About</a>
      </Link>
    </div>
  )
}
Run Code Online (Sandbox Code Playgroud)

MyLayout.js 组件

import Header from './Header'

const layoutStyle = {
  margin: 20,
  padding: 20,
  border: '1px solid #DDD'
}

export default function Layout(props) {
  return (
    <div style={layoutStyle}>
      <Header />
      {props.children}
    </div>
  )
}
Run Code Online (Sandbox Code Playgroud)

索引.js

import Layout from '../components/MyLayout.js'
import Link from 'next/link'

function getPosts() {
  return [
    { id: 'hello-nextjs', title: 'Hello Next.js' },
    { id: 'learn-nextjs', title: 'Learn Next.js is awesome' },
    { id: 'deploy-nextjs', title: 'Deploy apps with ZEIT' }
  ]
}

const PostLink = ({ post }) => (
  <li>
    <Link href="/p/[id]" as={`/p/${post.id}`}>
      <a>{post.title}</a>
    </Link>
    <style jsx>{`
      li {
        list-style: none;
        margin: 5px 0;
      }

      a {
        text-decoration: none;
        color: blue;
        font-family: 'Arial';
      }

      a:hover {
        opacity: 0.6;
      }
    `}</style>
  </li>
)

export default function Blog() {
  return (
    <Layout>
      <h1>My Blog</h1>
      <ul>
        {getPosts().map(post => (
          <PostLink key={post.id} post={post} />
        ))}
      </ul>
    </Layout>
  )
}
Run Code Online (Sandbox Code Playgroud)

包.json

{
  "name": "hello-next",
  "version": "1.0.0",
  "scripts": {
    "dev": "next",
    "build": "next build",
    "start": "next start -p $PORT",
    "export": "next export"
  },
  "license": "ISC",
  "dependencies": {
    "next": "latest",
    "react": "^16.12.0",
    "react-dom": "^16.12.0",
    "react-markdown": "^4.0.6"
  }
}
Run Code Online (Sandbox Code Playgroud)

编辑:我遵循了本指南nextjs.org/learn/basics/deploying-a-nextjs-app。但我使用“部署到您自己的环境”步骤。所以基本上与此存储库相同的结构github.com/zeit/next-learn-demo/tree/master/8-deploying

小智 9

我通过将以下内容添加到 next.config.js 解决了这个问题:

module.exports = {
  exportTrailingSlash: true,
}
Run Code Online (Sandbox Code Playgroud)

https://nextjs.org/docs/api-reference/next.config.js/exportPathMap#adding-a-trailing-slash

我想这取决于你的网络服务器。