【问题标题】:Why do I get 401 for static fies when using Express with React.js?为什么我在使用 Express 和 React.js 时得到 401 的静态文件?
【发布时间】:2020-08-10 15:57:26
【问题描述】:

设置:

  • 具有 express 的 Node.js 服务器在 localhost:3000 上运行(具有到活动目录的 ldap 会话)并使用包 node-expose-sspi 的 SSO
  • IIS 反向代理在 localhost:80 上运行并重定向到节点服务器 localhost:3000
  • 在端口 localhost:3001 上开发一个 React Dev 服务器,在 package.json 中有一个代理

问题

我有一个 node express 服务器,它为我的 react 应用程序的构建文件夹提供服务:

app.use(express.static(path.join(__dirname, "client", "build")));


app.get("/", (req, res) => {
  res.sendFile(path.join(__dirname, "client", "build", "index.html"));
});

react 应用程序本身只是一个简单的 hello world 示例。但是当我通过反向代理访问我的服务器时:http://myservername 页面打开但我在控制台中看到此错误:

GET http://myserver/static/js/2.d0df15ed.chunk.js net::ERR_ABORTED 401(未授权)

页面加载。

我有一个名为/api/me 的测试路线。此路由只是从 SSO(单点登录)获取用户并将其作为 json 返回。

现在我有 3 种不同的场景:

  • 客户端只是通过简单的 fetch 请求调用这个 api,然后说 <p>Hello {username}</p> ==> 它只显示“Hello”和静态文件的 401:当我打开静态文件的路径时直接浏览器,就可以了!
  • 当我直接在浏览器中打开路由时,我得到了我期望的 json
  • 当我在 react 开发服务器 (localhost:3001) 上打开路由时,我得到 "Hello 所以他也可以工作。

我使用 procmon 登录了网络服务器,这就是我发现的:

我像这样在节点中服务器我的应用程序:

app.use( "/", express.static(path.join(__dirname, "client", "build", "index.html")) );

所以找不到路径是因为路径不正确应该是AttractiveDirectory\client\build\static...`

也许这就是错误所在?

现在我真的不知道如何解决这个问题。我翻阅了相反的日志,但没有任何信息。因此,在客户端上使用 fetch 时,身份验证似乎以某种奇怪的方式不起作用。但是为什么即使打开站点并且仅针对静态文件,我也会得到 401?

我是否在 express.static 方面犯了错误?

【问题讨论】:

    标签: node.js reactjs iis reverse-proxy


    【解决方案1】:

    请确保网站根目录已被授予对IUSR帐户的完全访问权限。

    另外,尝试在你的项目根目录下配置IIS URL Rewrite扩展。
    添加包含以下内容的webconfig 文件。

        <?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>
    

    注意:在应用上述更改之前,请安装 URL Rewrite 扩展。
    https://www.iis.net/downloads/microsoft/url-rewrite
    最后,查看以下链接了解详情。
    https://gist.github.com/maxan/0d124ed677ebe41e1aeaf4a9e1e6aa45
    https://medium.com/@mateioprea/setting-up-a-react-app-with-react-router-in-iis-71cb86aee376
    如果有什么我可以帮忙的,请随时告诉我。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-08-20
      • 1970-01-01
      • 2017-03-30
      • 2014-02-23
      • 1970-01-01
      • 1970-01-01
      • 2012-05-05
      • 1970-01-01
      相关资源
      最近更新 更多