我有一个 React JS 应用程序,带有 React Router。在开发过程中,npm start,我没有遇到任何问题。我像往常一样访问以下地点。
http://localhost:3000
由于路由代码,它变成了
http://localhost:3000/index
应用程序加载得很好。此时,
然后,稍后,我执行 npm 构建,进入此构建文件夹,然后执行 npm start,再次执行相同的操作。该应用程序运行得很好。我重新加载,运行正常。到目前为止没有什么可抱怨的。
问题部分。
然后我决定将该应用程序部署到 azure Web 应用程序。该应用程序运行良好。我去这个网站。
https://randomstuffreactjsappsept24.azurewebsites.net
并且由于路由代码,它变成了
https://randomstuffreactjsappsept24.azurewebsites.net/index
并且,网站加载。
此时,如果我点击重新加载(问题!!),它会尝试重新加载,
https://randomstuffreactjsappsept24.azurewebsites.net/index
我收到以下错误。
The resource you are looking for has been removed, had its name changed, or is temporarily unavailable.
现在,如果我删除“/index”并加载原始网址,
https://randomstuffreactjsappsept24.azurewebsites.net
该网站加载得很好,没有问题。注意,你可以自己看看。这是一个实时网站。 (但是当然,由于路由代码,它变成了)
https://randomstuffreactjsappsept24.azurewebsites.net/index
现在,只要我不重新加载网站,网站就会继续运行。为什么会出现这种情况?
这是项目中主 index.js 页面的代码。
ReactDOM.render(
<BrowserRouter>
<Switch>
<Route path="/index" render={(props) => <Index {...props} />} />
<Redirect to="/index" />
</Switch>
</BrowserRouter>,
document.getElementById("root")
);
完整的应用程序可在此处获取 - https://github.com/Jay-study-nildana/RandomStuffReactJSApp
更新2
我决定尝试另一个完全由另一个来源创建的 React 应用程序。再次出现同样的问题,我有一个实时网站可以展示。
所以,它绝对是“唯一”在部署后发生的事情。
根据:https://github.com/react-boilerplate/react-boilerplate/issues/1612 您必须放置: 只需将以下名为 web.config 的文件放在您的 wwwroot 文件夹下即可:
<?xml version="1.0"?>
<configuration>
<system.webServer>
<rewrite>
<rules>
<rule name="React Routes" stopProcessing="true">
<match url=".*" />
<conditions logicalGrouping="MatchAll">
<add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
<add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
<add input="{REQUEST_URI}" pattern="^/(api)" negate="true" />
</conditions>
<action type="Rewrite" url="/" />
</rule>
</rules>
</rewrite>
</system.webServer>
</configuration>
将
web.config
文件添加到 Azure 目录。
我昨天在我的 Azure Web 应用程序部署中使用自定义构建后遇到了这个问题(使用
skip_app_build = false
跳过它并在之前的工作中构建它)。
我的错误是我的
staticwebapp.config.json
文件未位于公共文件夹中 -> 它未正确部署。插入任何路线后,azure 会抛出 404。
只需将
staticwebapp.config.json
移至公共文件夹即可。
我也有同样的问题。我们的 Azure App Servive 运行 PHP 和 Apache,因此我们使用了一个
.htaccess
文件,就像 Create React App 的部署文档中建议的那样。 https://create-react-app.dev/docs/deployment#serving-apps-with-client-side-routing
Options -MultiViews
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.html [QSA,L]
将
.htaccess
添加到公共文件夹,这将阻止您刷新这些类型的 Aapp 服务。