无框架Node.js应用部署Azure后路由失效,请求配置指导
解决Azure上无框架Node.js应用的路由访问问题
这个问题我之前帮朋友排查过,核心原因是Azure Web Apps用IIS作为反向代理,默认会优先尝试匹配物理文件——当你访问/login时,IIS找不到对应的login文件或目录,就直接返回了404错误,根本没把请求转发给你的Node.js应用处理。下面是具体的解决步骤:
1. 修改web.config添加URL重写规则
你需要在web.config中添加重写规则,让IIS把所有非静态文件的请求都转发给你的Node.js入口文件(比如server.js,如果你的入口文件名不同,记得替换)。更新后的配置如下:
<?xml version="1.0"?> <configuration> <system.webServer> <staticContent> <mimeMap fileExtension=".html" mimeType="text/html" /> </staticContent> <!-- 添加URL重写规则 --> <rewrite> <rules> <rule name="Node.js Routes" stopProcessing="true"> <!-- 匹配所有URL路径 --> <match url="(.*)" /> <conditions logicalGrouping="MatchAll"> <!-- 排除已存在的物理文件 --> <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" /> <!-- 排除已存在的物理目录 --> <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" /> </conditions> <!-- 转发请求到Node.js入口文件 --> <action type="Rewrite" url="server.js" /> </rule> </rules> </rewrite> </system.webServer> </configuration>
规则解释:
<match url="(.*)" />:匹配所有URL路径<conditions>中的两个规则:确保静态文件(比如index.html)仍由IIS直接处理,保证性能;只有不存在的文件/目录请求才会转发给Node.js<action>:把符合条件的请求重写到你的Node.js入口文件,让应用自己处理路由逻辑
2. 确认Node.js应用的路由逻辑正确
确保你的入口文件(比如server.js)里正确处理了/login路由,同时要注意监听Azure提供的环境变量端口,示例代码如下:
const http = require('http'); const fs = require('fs'); const path = require('path'); const server = http.createServer((req, res) => { let filePath = '.' + req.url; // 处理根路由和login路由 if (filePath === './') { filePath = './index.html'; } else if (filePath === './login') { filePath = './login.html'; } const extname = path.extname(filePath); let contentType = 'text/html'; switch (extname) { case '.js': contentType = 'text/javascript'; break; case '.css': contentType = 'text/css'; break; } fs.readFile(filePath, (error, content) => { if (error) { if(error.code === 'ENOENT') { res.writeHead(404); res.end('File not found'); } else { res.writeHead(500); res.end('Server Error: ' + error.code); } } else { res.writeHead(200, { 'Content-Type': contentType }); res.end(content, 'utf-8'); } }); }); // 监听Azure自动设置的端口,不能硬编码 const PORT = process.env.PORT || 3000; server.listen(PORT, () => { console.log(`Server running on port ${PORT}`); });
3. 额外检查项
- 确认Azure上的Node.js版本和本地一致:在Azure门户的Web App -> 配置 -> 应用设置里,找到
WEBSITE_NODE_DEFAULT_VERSION,设置成你本地使用的版本(比如18.x) - 部署时确认所有文件都上传成功:可以通过Azure门户的「高级工具」->「Kudu」->「调试控制台」->「文件管理器」,查看部署后的文件结构是否完整
内容的提问来源于stack exchange,提问作者Azam Maqsood
相关产品推荐
相关产品推荐

