我有一个 React JS 应用程序,带有 React Router。在开发过程中,npm start,我没有遇到任何问题。我像往常一样访问以下位置。
http://localhost:3000
由于路由代码,它变成了
http://localhost:3000/index
应用程序加载得很好。此时,
- 我点击重新加载,应用程序继续正常运行。
- 我手动链接或加载“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://auth0tokenreactjsappprivatesept25.azurewebsites.net/external-api ,在网络应用程序中,它工作正常。如果我此时重新加载,它会显示“您正在查找的资源已被删除、名称已更改或暂时不可用。”
- 我从应用程序内访问http://localhost:3000/external-api,它工作正常。而且,如果我重新加载,它加载得很好。
因此,这绝对是“仅”在部署后发生的事情。
最佳答案
根据: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 目录
关于reactjs - 仅在部署到 Azure Web 应用程序后,React JS 应用程序路由问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64051157/