首页 > 解决方案 > 为什么我在使用 Express 和 React.js 时得到 401 的静态文件?

问题描述

设置:

问题

我有一个 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 种不同的场景:

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

在此处输入图像描述

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

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

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

也许这就是错误所在?

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

express.static我在事情方面犯了错误吗?

标签: node.jsreactjsiisreverse-proxy

解决方案


请确保网站的根目录已被授予对该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 重写扩展。
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
随意让我知道有什么我可以帮忙的。


推荐阅读