javascript - 使用 Nginx 在刷新 404 上部署后创建 React 应用程序中断

标签 javascript reactjs nginx ibm-cloud create-react-app

我正在使用create-react-app,它在我的本地运行良好,没有任何问题。当我将其部署在 IBM Cloud 上时,登录后,当我刷新页面时,它会给出 404 未找到错误 之前工作正常,不确定发生了什么。

我看到了很多相关的问题,我试图解决但没有解决的问题如下

1. 创建了 static.json

{
  "root": "build/",
  "routes": {
    "/**": "index.html"
  }
}

<强>2。我有这个设置

devServer: {
    historyApiFallback: true,
    contentBase: './',
    hot: true
  },

<强>3。我尝试在路由器周围添加,但没有成功

import React, { Component } from 'react';
import styled from 'styled-components';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';

    class App extends Component {
      render() {
        return (
          <>
            <Router>
              <Switch>
                <Route exact path="/" component={SignUp} />
                <Route path="/some" component={Some} />
              </Switch>
            </Router>
            </>
        );
      }
    }

    export default App;

<强>4。我尝试添加以下内容

import { HashRouter } from 'react-router-dom'

<HashRouter>
  <App/>
</HashRouter>

这些似乎都不适合我。有什么建议

最佳答案

当将 build/ 输出作为静态站点提供服务时,您必须将 nginx 配置为始终提供 index.html (否则,它将尝试匹配 url静态文件夹/文件的路径,该文件夹/文件不存在)。有关此行为的更多信息可以在 create-react-app docs 中找到。

如果您使用 nginx docker 镜像来为您的站点提供服务,则需要设置以下default.conf:

server {
    location / {
        root   /usr/share/nginx/html;
        index  index.html index.htm;
        try_files $uri $uri/ /index.html;
    }

    location ~ ^/$ {
        rewrite  ^.*$  /index.html  last;
    }
    listen       80;
    server_name  localhost;

    # redirect server error pages to the static page /50x.html
    #
    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/share/nginx/html;
    }
}

请注意 rewrite ^.*$/index.html 部分,该部分修改任何传入调用并提供 index.html

您的最小 Dockerfile 将如下所示:

FROM nginx
COPY default.conf /etc/nginx/conf.d/default.conf
COPY build/ /usr/share/nginx/html/

关于javascript - 使用 Nginx 在刷新 404 上部署后创建 React 应用程序中断,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53567077/

相关文章:

javascript - 您如何捕获jQuery插件内部引发的错误?

html - 是否可以将 React 单页网站导出为 HTML?

nginx - 检查 Kubernetes 集群上 NGINX 中加载的 SSL 证书的值

php - apache .htaccess 到 nginx 重写规则

ssl - 将 Let's Encrypt 与由 Nginx 通配符处理的子域一起使用

javascript - 通过单击链接突出显示另一页的元素

javascript - CNET 等社交分享按钮

javascript - 在对象数组中获取重复项

reactjs - 如何在 redux-persist 中正确使用 getStoredState

reactjs - 获取React组件的类型propTypes定义