React 应用程序将在 prod 的刷新页面上给出 404,但在 dev 中不会

IT技术 reactjs react-router
2021-05-09 00:39:01

我有一个 React 应用程序,我的导航中有一个 404 问题,如果我尝试刷新一个不是根页面的页面,它会给我一个 404。

事情是它只发生在我身上,而不是在开发上。

在开发环境中,我使用npm start,在生产环境中,我使用serve build.

这使得调试更加复杂,因为我失去了用于调试的热重载选项。每次进行更改时,我都必须编译我的 docker 映像。

这是我的一些代码:

<BrowserRouter>
        <div>

            <Switch>
                <Route exact path="/premiere-connexion" component={FirstLoginLayout}/>
                {(user.state === "1" && window.location.pathname === "/premiere-connexion") &&
                <Redirect to="/premiere-connexion"/>}
                <PrivateRoute path="/bo" component={BackOfficeLayout} profiles={["ADMIN"]}/>
                <Route exact path="/" component={Customer}/>
                <Redirect to="/"/>
            </Switch>
            }
        </div>
    </BrowserRouter>

任何想法我应该如何在本地复制它?

2个回答

根据@hbentlov 的建议,我解决了这个问题serve.json,在public/文件夹中创建了一个文件内容如下:

{
  "rewrites": [{
    "source": "**",
    "destination": "/index.html"
  }]
}

我最终来到这里,因为我遇到了同样的问题;当您直接调用 React Router 地址时,当您在 docker 上运行 react 时会收到 404 错误。

解决方案是告诉您的 nginx 将不存在的 url 发送到 index.html(这非常容易)

您需要创建一个nginx.conf文件(在我的情况下在 Dockerfile 旁边)并将其复制到容器内的 /etc/nginx/nginx.conf 中。

这里是 nginx.conf

# auto detects a good number of processes to run
worker_processes auto;

#Provides the configuration file context in which the directives that affect connection processing are specified.
events {
    # Sets the maximum number of simultaneous connections that can be opened by a worker process.
    worker_connections 8000;
    # Tells the worker to accept multiple connections at a time
    multi_accept on;
}


http {
    # what times to include
    include       /etc/nginx/mime.types;
    # what is the default one
    default_type  application/octet-stream;

    # Sets the path, format, and configuration for a buffered log write
    log_format compression '$remote_addr - $remote_user [$time_local] '
        '"$request" $status $upstream_addr '
        '"$http_referer" "$http_user_agent"';

    server {
        # listen on port 80
        listen 80;
        # save logs here
        access_log /var/log/nginx/access.log compression;

        # where the root here
        root /usr/share/nginx/html;
        # what file to server as index
        index index.html index.htm;

        location / {
            # First attempt to serve request as file, then
            # as directory, then fall back to redirecting to index.html
            try_files $uri $uri/ /index.html;
        }

        # Media: images, icons, video, audio, HTC
        location ~* \.(?:jpg|jpeg|gif|png|ico|cur|gz|svg|svgz|mp4|ogg|ogv|webm|htc)$ {
          expires 1M;
          access_log off;
          add_header Cache-Control "public";
        }

        # Javascript and CSS files
        location ~* \.(?:css|js)$ {
            try_files $uri =404;
            expires 1y;
            access_log off;
            add_header Cache-Control "public";
        }

        # Any route containing a file extension (e.g. /devicesfile.js)
        location ~ ^.+\..+$ {
            try_files $uri =404;
        }
    }
}

这就是您应用它的方式:添加COPY nginx.conf /etc/nginx/nginx.conf到您的 Dockerfile 中。

我的Dockerfile看起来像这样:

# build environment
FROM node:13.12.0-alpine as build
WORKDIR /app
ENV PATH /app/node_modules/.bin:$PATH
COPY package.json ./
COPY package-lock.json ./
RUN npm ci --silent
RUN npm install react-scripts@3.4.1 -g --silent
COPY . ./
RUN npm run build


# production environment
FROM nginx:stable-alpine
# Nginx configuration
COPY nginx.conf /etc/nginx/nginx.conf

COPY --from=build /app/build /usr/share/nginx/html
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]

该行 try_files $uri $uri/ /index.html;告诉 nginx 回退到 index.html

希望它能帮助到这里的其他人