node.js - 为什么我在使用 Express 和 React.js 时得到 401 的静态文件?
问题描述
设置:
- 具有 express 的 Node.js 服务器在 localhost:3000 上运行(具有到活动目录的 ldap 会话)并使用 SSO 和包
node-expose-sspi
- 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 种不同的场景:
- 客户端只是用简单的获取请求调用这个 api,然后说
<p>Hello {username}</p>
==> 它只显示“Hello”和静态文件的 401:当我直接在浏览器中打开静态文件的路径时,它就可以工作了! - 当我直接在浏览器中打开路由时,我得到了我期望的 json
- 当我在反应开发服务器 (localhost:3001) 上打开路由时,我得到 "Hello <myusername" => 所以他也可以工作。
我用 procmon 记录了网络服务器,这就是我发现的:
我像这样在节点中服务器我的应用程序:
app.use( "/", express.static(path.join(__dirname, "client", "build", "index.html")) );
所以找不到路径是因为路径不正确应该是 AttractiveDirectory\client\build\static...`
也许这就是错误所在?
现在我真的不知道我该如何解决这个问题。我翻阅了相反的日志,但没有任何信息。因此,在客户端上使用 fetch 时,身份验证似乎以某种奇怪的方式不起作用。但是为什么即使打开站点并且仅针对静态文件,我也会得到 401?
express.static
我在事情方面犯了错误吗?
解决方案
请确保网站的根目录已被授予对该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
随意让我知道有什么我可以帮忙的。
推荐阅读
- ios - 如何在 Swift 中自动布局按钮
- javascript - 在子文件夹中的 VS Code 中设置启动任务
- java - AsyncTask 加载数据时动画冻结
- javascript - ng-show 在成功回调函数中停止工作
- ms-access - MS Access 实时搜索中的 VBA 不起作用
- mysql - 将行转换为sql server中的列错误结果
- python - API Gateway 触发的 AWS Lambda 上的二进制数据
- javascript - 页面上的 Javascript 多个 DateRangePicker 元素
- apache-spark - Spark连续处理模式不读取所有kafka主题分区
- angular - canActivate 文档示例 - 一般理解