使用 React Router 进行 Azure 静态应用程序路由配置

Sno*_*opy 14 reactjs azure-static-website-routing azure-static-web-app

我正在尝试在天蓝色上配置静态应用程序,但很难正确路由。当我导航到/lti/login/应用程序内时,它工作正常。但如果我刷新它会抛出 404,这告诉我我的routes.json设置不正确(也许)。我希望有人能对此有所启发。

routes.json

{
    "routes": [
      {
        "route": "/",
        "serve":"/"
  
      },
      {
        "route": "/lti/login/*",
        "serve":"/lti/login"

      }
     
    ]
  
  }
Run Code Online (Sandbox Code Playgroud)

App.js

   <Router>
      <div>
        <ul>
          <li>
            <Link to="/">Home</Link>
          </li>
          <li>
            <Link to="/lti/login/">About</Link>
          </li>
        </ul>

        <hr />

        {/* A <Switch> looks through its children <Route>s and
          renders the first one that matches the current URL. */}
        <Switch>
          <Route exact path="/">
            <Form />
          </Route>
          <Route path="/lti/login/*"> <----- If I navigate to this within the app and then refresh it throws a 404. 
            <About />
          </Route>
        </Switch>
      </div>
    </Router>
Run Code Online (Sandbox Code Playgroud)

Ela*_*Tal 17

至于最新文档,不推荐使用路由:

以前用于配置路由的routes.json 已弃用。按照本文所述使用 staticwebapp.config.json 为静态 Web 应用程序配置路由和其他设置。

现在您需要在 staticwebapp.config.json 中添加 navigationFallback 部分,如下所示:

{
"navigationFallback": {
    "rewrite": "index.html",
    "exclude": ["*.{svg,png,jpg,gif}","*.{css,scss}","*.js"]
  }}
Run Code Online (Sandbox Code Playgroud)

您可以在这里找到完整的文档:

https://learn.microsoft.com/en-us/azure/static-web-apps/configuration#fallback-routes


小智 7

按照最新的“Azure Static Web Apps 配置”,我为部署到 Azure Static Web Apps 的 React 做了一个配置示例: staticwebapp.config.json

{
    "routes": [
        {
            "route": "/admin",
            "allowedRoles": ["administrator"]
        }
    ],
    "navigationFallback": {
      "rewrite": "index.html",
      "exclude": ["/static/media/*.{png,jpg,gif,svg}", "/static/css/*"]
    },
    "responseOverrides": {
      "400": {
        "rewrite": "/invalid-invitation-error.html"
      },
      "401": {
        "redirect": "/login",
        "statusCode": 302
      },
      "403": {
        "rewrite": "/custom-forbidden-page.html"
      },
      "404": {
        "rewrite": "/404.html"
      }
    },
    "globalHeaders": {
      "content-security-policy": "default-src https: 'unsafe-eval' 'unsafe-inline'; object-src 'none'"
    },
    "mimeTypes": {
      ".json": "text/json"
    }
  }
Run Code Online (Sandbox Code Playgroud)


svi*_*ct4 0

对于 React,您需要它来提供 index.html 文件。

这是一个示例routes.json配置:

{
  "routes": [
    {
      "route": "/*",
      "serve": "/index.html",
      "statusCode": 200
    }
  ],
  "platformErrorOverrides": [
    { "errorType": "NotFound", "serve": "/404" },
    {
      "errorType": "Unauthenticated",
      "statusCode": "302",
      "serve": "/login"
    }
  ],
  "mimeTypes": {
    "json": "application/json"
  }
}
Run Code Online (Sandbox Code Playgroud)